HardNo. 2163
Minimum Difference in Sums After Removal of Elements — LeetCode 2163 Python Solution
- Pattern
- Heap / Priority Queue
- Topics
- Array, Dynamic Programming, Heap (Priority Queue)
- Reading time
- 5 min
- Source
- leetcode.com
The problem
You are given a 0-indexed integer array nums consisting of 3 * n elements. You are allowed to remove any subsequence of elements of size exactly n from nums.
Example
- Input
- nums = [3,1,2]
- Output
- -1
- Explanation
- Here, nums has 3 elements, so n = 1.
Python solution
class Solution:
def minimumDifference(self, nums: List[int]) -> int:
m = len(nums)
n = m // 3
s = 0
pre = [0] * (m + 1)
q1 = []
for i, x in enumerate(nums[: n * 2], 1):
s += x
heappush(q1, -x)
if len(q1) > n:
s -= -heappop(q1)
pre[i] = s
s = 0
suf = [0] * (m + 1)
q2 = []
for i in range(m, n, -1):
x = nums[i - 1]
s += x
heappush(q2, x)
if len(q2) > n:
s -= heappop(q2)
suf[i] = s
return min(pre[i] - suf[i + 1] for i in range(n, n * 2 + 1))Complexity
- Time
- O(n × log n)
- Space · auxiliary
- O(n)
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2163. Minimum Difference in Sums After Removal of Elements is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0871 | Minimum Number of Refueling Stops | Hard |
| 1388 | Pizza With 3n Slices | Hard |
| 1425 | Constrained Subsequence Sum | Hard |
| 1687 | Delivering Boxes from Storage to Ports | Hard |
| 1696 | Jump Game VI | Medium |
| 2617 | Minimum Number of Visited Cells in a Grid | Hard |
Frequently asked questions
- How hard is LeetCode 2163. Minimum Difference in Sums After Removal of Elements?
LeetCode 2163. Minimum Difference in Sums After Removal of Elements is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2163. Minimum Difference in Sums After Removal of Elements?
The Python solution on this page runs in O(n × log n).
- What is the space complexity of LeetCode 2163. Minimum Difference in Sums After Removal of Elements?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2163. Minimum Difference in Sums After Removal of Elements cover?
LeetCode 2163. Minimum Difference in Sums After Removal of Elements is tagged Array, Dynamic Programming and Heap (Priority Queue) on LeetCode.