Leetcode Problem 2163. Minimum Difference in Sums After Removal of Elements

2163. Minimum Difference in Sums After Removal of Elements

Leetcode Solutions

Priority Queue Approach

  1. Initialize two priority queues: a max-heap for the smallest n elements (left part) and a min-heap for the largest n elements (right part).
  2. Calculate the initial sum of the first n elements and the last n elements, and add them to their respective heaps.
  3. Iterate over the array from the n-th element to the (2n-1)-th element, updating the heaps and sums accordingly.
  4. For each element, if it's smaller than the max-heap's top, replace the top with this element and update the sum for the left part. Similarly, if it's larger than the min-heap's top, replace the top with this element and update the sum for the right part.
  5. After each update, calculate the current difference between the sums of the smallest and largest n elements and update the minimum difference if necessary.
  6. Return the minimum difference after iterating through the array.
UML Thumbnail

Sliding Window with Multiset Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...