#2163

Minimum Difference in Sums After Removal of Elements

Hard
ArrayDynamic ProgrammingHeap (Priority Queue)HeapDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal approach uses a min-heap and max-heap to efficiently find the minimum sum of n elements and the maximum sum of n elements from the remaining elements after removing n elements. This significantly reduces the time complexity.

⚙️

Algorithm

4 steps
  1. 1Step 1: Use a max-heap to keep track of the smallest n elements from the first 2n elements.
  2. 2Step 2: Use a min-heap to keep track of the largest n elements from the last 2n elements.
  3. 3Step 3: Calculate the sums of the two heaps and find the difference.
  4. 4Step 4: Return the minimum difference found.
solution.py23 lines
1# Full working Python code
2import heapq
3
4def minDifference(nums):
5    n = len(nums) // 3
6    max_heap = []  # To store the smallest n elements
7    min_heap = []  # To store the largest n elements
8    
9    # First half processing for max_heap
10    for i in range(2 * n):
11        heapq.heappush(max_heap, nums[i])
12        if len(max_heap) > n:
13            heapq.heappop(max_heap)
14    sum_first = sum(max_heap)
15    
16    # Second half processing for min_heap
17    for i in range(3 * n - 1, n - 1, -1):
18        heapq.heappush(min_heap, -nums[i])
19        if len(min_heap) > n:
20            heapq.heappop(min_heap)
21    sum_second = -sum(min_heap)
22    
23    return sum_first - sum_second

Complexity note: The time complexity is O(n log n) due to the heap operations for maintaining the top n elements. The space complexity is O(n) because we are storing elements in heaps.

  • 1The minimum difference can be achieved by carefully selecting which n elements to remove.
  • 2Using heaps allows us to efficiently track the smallest and largest sums needed for the calculation.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.