Skip to content

2599. Make the Prefix Sum Non-negative 👍

  • Time: $O(n\log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int makePrefSumNonNegative(vector<int>& nums) {
    int ans = 0;
    long long prefix = 0;
    priority_queue<int, vector<int>, greater<>> minHeap;

    for (const int num : nums) {
      prefix += num;
      if (num < 0)
        minHeap.push(num);
      while (prefix < 0) {
        prefix -= minHeap.top(), minHeap.pop();
        ++ans;
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int makePrefSumNonNegative(int[] nums) {
    int ans = 0;
    long prefix = 0;
    Queue<Integer> minHeap = new PriorityQueue<>();

    for (final int num : nums) {
      prefix += num;
      if (num < 0)
        minHeap.offer(num);
      while (prefix < 0) {
        prefix -= minHeap.poll();
        ++ans;
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def makePrefSumNonNegative(self, nums: List[int]) -> int:
    ans = 0
    prefix = 0
    minHeap = []

    for num in nums:
      prefix += num
      if num < 0:
        heapq.heappush(minHeap, num)
      while prefix < 0:
        prefix -= heapq.heappop(minHeap)
        ans += 1

    return ans