Complete the code to add a number to the max heap.
maxHeap.[1](num);In this implementation, the max heap uses the method Push to add elements.
Complete the code to balance the heaps when max heap has more elements.
if (maxHeap.Count > minHeap.Count + [1]) { minHeap.Push(maxHeap.Pop()); }
We balance heaps when max heap has more than one extra element compared to min heap.
Fix the error in the code to get the median when heaps are balanced.
return (maxHeap.Peek() + minHeap.[1]()) / 2.0;
To get the median without removing elements, use Peek on both heaps.
Fill both blanks to correctly add a number to the appropriate heap.
if (minHeap.Count > 0 && num > minHeap.[1]()) { minHeap.[2](num); } else { maxHeap.Push(num); }
We compare with the smallest element in minHeap using Peek and add to minHeap using Push.
Fill all three blanks to correctly rebalance heaps and return the median.
if (maxHeap.Count > minHeap.Count + [1]) { minHeap.Push(maxHeap.[2]()); } else if (minHeap.Count > maxHeap.Count + [3]) { maxHeap.Push(minHeap.Pop()); } if (maxHeap.Count == minHeap.Count) { return (maxHeap.Peek() + minHeap.Peek()) / 2.0; } else { return maxHeap.Peek(); }
We rebalance when size difference is more than 1. We move elements using Pop from maxHeap and add to minHeap. The same size difference check applies for minHeap.
