[LeetCode] Make the Prefix Sum Non-negative

2599. Make the Prefix Sum Non-negative

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.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int makePrefSumNonNegative(vector<int>& nums) {
priority_queue<int, vector<int>, greater<int>> q;
long long res = 0, sum = 0;
for(int i = 0; i < nums.size(); i++) {
sum += nums[i];
if(nums[i] <= 0) q.push(nums[i]);
while(sum < 0) {
sum -= q.top(); q.pop(); res += 1;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/04/11/PS/LeetCode/make-the-prefix-sum-non-negative/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.