Make the Prefix Sum Non-negative — LeetCode 2599 Python Solution

MediumLeetCode PremiumGreedyArrayHeap (Priority Queue)
Problem
#2599
Reading time
2 min

The problem

You are given a 0-indexed integer array nums. You can apply the following operation any number of times: Pick any element from nums and put it at the end of nums.

Example

Input
nums = [2,3,-5,4]
Output
0
Explanation
we do not need to do any operations.

Python solution

Python
class Solution:
    def makePrefSumNonNegative(self, nums: List[int]) -> int:
        h = []
        ans = s = 0
        for x in nums:
            s += x
            if x < 0:
                heappush(h, x)
            while s < 0:
                s -= heappop(h)
                ans += 1
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n), where n is the length of the array nums auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2599. Make the Prefix Sum Non-negative 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 2599. Make the Prefix Sum Non-negative?
LeetCode 2599. Make the Prefix Sum Non-negative is rated Medium on LeetCode.
What is the time complexity of LeetCode 2599. Make the Prefix Sum Non-negative?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2599. Make the Prefix Sum Non-negative?
The Python solution on this page uses O(n), where n is the length of the array nums auxiliary space.
What topics does LeetCode 2599. Make the Prefix Sum Non-negative cover?
LeetCode 2599. Make the Prefix Sum Non-negative is tagged Greedy, Array and Heap (Priority Queue) on LeetCode.
Is LeetCode 2599. Make the Prefix Sum Non-negative a premium problem?
Yes. LeetCode 2599. Make the Prefix Sum Non-negative is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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