Minimum Difference in Sums After Removal of Elements — LeetCode 2163 Python Solution

HardArrayDynamic ProgrammingHeap (Priority Queue)
Problem
#2163
Reading time
5 min

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

Python
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

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

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

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 \times \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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview