public IList <IList <int> > GetSkyline(int[][] buildings) { var points = buildings.SelectMany((building) => new[] { new Point { IsLeft = true, Other = building[1], X = building[0], Y = building[2] }, new Point { IsLeft = false, X = building[1], Y = building[2] } }).OrderBy((point) => point, new PointComparer()); var current = new MaxPriorityQueue <Point>(); var skyline = new List <IList <int> >(); foreach (var point in points) { if (point.IsLeft) { if (!current.IsEmpty && point.Y <= current.Max.Y) { while (!current.IsEmpty && current.Max.Other < point.X) { current.DeleteMax(); } } if (current.IsEmpty || point.Y > current.Max.Y) { skyline.Add(new[] { point.X, point.Y }); } current.Add(point); } else { while (!current.IsEmpty && current.Max.Other <= point.X) { current.DeleteMax(); } var height = current.IsEmpty ? 0 : current.Max.Y; if (height != skyline[skyline.Count - 1][1]) { skyline.Add(new[] { point.X, current.IsEmpty ? 0 : current.Max.Y }); } } } return(skyline); }
public void MaxPriorityQueueTest() { var pq = new MaxPriorityQueue <string>(9); var results = new List <string>(); pq.Insert("P"); pq.Insert("Q"); pq.Insert("E"); results.Add(pq.DeleteMax()); pq.Insert("X"); pq.Insert("A"); pq.Insert("M"); results.Add(pq.DeleteMax()); pq.Insert("P"); pq.Insert("L"); pq.Insert("E"); results.Add(pq.DeleteMax()); }
public int MaxProfit(int k, int[] prices) { var peak = 0; var valley = 0; var candidates = new Stack <Tuple <int, int> >(); var profits = new MaxPriorityQueue <int>(prices.Length); while (peak < prices.Length) { for (valley = peak; valley < prices.Length - 1 && prices[valley] >= prices[valley + 1]; valley++) { ; } for (peak = valley + 1; peak < prices.Length && prices[peak] >= prices[peak - 1]; peak++) { ; } while (candidates.Count > 0 && prices[valley] < prices[candidates.Peek().Item1]) { profits.Add(prices[candidates.Peek().Item2 - 1] - prices[candidates.Peek().Item1]); candidates.Pop(); } while (candidates.Count > 0 && prices[peak - 1] >= prices[candidates.Peek().Item2 - 1]) { profits.Add(prices[candidates.Peek().Item2 - 1] - prices[valley]); valley = candidates.Peek().Item1; candidates.Pop(); } candidates.Push(new Tuple <int, int>(valley, peak)); } while (candidates.Count > 0) { profits.Add(prices[candidates.Peek().Item2 - 1] - prices[candidates.Peek().Item1]); candidates.Pop(); } var max = 0; for (; k > 0 && !profits.IsEmpty; k--) { max += profits.DeleteMax(); } return(max); }
public void AddNum(int num) { if (maxHeap.Count == 0 || num < maxHeap.Max) { maxHeap.Add(num); } else { minHeap.Add(num); } if (maxHeap.Count < minHeap.Count) { maxHeap.Add(minHeap.DeleteMin()); } else if (maxHeap.Count > minHeap.Count + 1) { minHeap.Add(maxHeap.DeleteMax()); } }