Make the Prefix Sum Non-negative Problem
Description
LeetCode Problem 2599.
You are given a 0-indexed integer array nums. You can apply the following operation any number of times:
- Pick any element from
numsand put it at the end ofnums.
The prefix sum array of nums is an array prefix of the same length as nums such that prefix[i] is the sum of all the integers nums[j] where j is in the inclusive range [0, i].
Return the minimum number of operations such that the prefix sum array does not contain negative integers. The test cases are generated such that it is always possible to make the prefix sum array non-negative.
Example 1:
Input: nums = [2,3,-5,4]
Output: 0
Explanation: we do not need to do any operations.
The array is [2,3,-5,4]. The prefix sum array is [2, 5, 0, 4].
Example 2:
Input: nums = [3,-5,-2,6]
Output: 1
Explanation: we can do one operation on index 1.
The array after the operation is [3,-2,6,-5]. The prefix sum array is [3, 1, 7, 2].
Constraints:
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Solution
Approach: Greedy + Priority Queue (Min Heap)
Moving an element to the end of the array helps only when it is negative, and the most negative one helps most. Scan the array while maintaining the prefix sum s. Push every negative number into a min heap. Whenever s becomes negative, pop the smallest value from the heap, subtract it from s (as if it had been moved to the end), and count one operation. Repeat until s is non-negative again.
Complexity: time O(n log n), space O(n), where n is the length of nums.
from heapq import heappop, heappush
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