Make the Prefix Sum Non-negative - 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.

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.

Input & Output

Example 1 — Mixed Values
$ Input: nums = [2,-1,2]
Output: 0
💡 Note: Prefix sums are [2,1,3] - all non-negative, so no operations needed
Example 2 — Needs Rearrangement
$ Input: nums = [3,-5,4]
Output: 1
💡 Note: Prefix sums are [3,-2,2]. When sum becomes -2, we move -5 to end: [3,4,-5] with prefix sums [3,7,2]
Example 3 — Multiple Negatives
$ Input: nums = [1,-1,-1,1]
Output: 1
💡 Note: At position 2, prefix sum becomes -1. We move the smallest element (-1) to end, requiring 1 operation

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • The sum of all elements in nums is non-negative

Visualization

Tap to expand
Make the Prefix Sum Non-negative INPUT nums array: 2 idx 0 -1 idx 1 2 idx 2 Prefix Sums: 2 1 3 prefix[0] = 2 prefix[1] = 2+(-1) = 1 prefix[2] = 1+2 = 3 All prefix sums >= 0 Already valid! ALGORITHM STEPS 1 Initialize Min-Heap Track smallest elements 2 Iterate & Sum Build running prefix sum 3 Check Negative If sum < 0, pop min element 4 Count Operations Each pop = 1 operation Min-Heap State: -1 2 2 Heap tracks negative values FINAL RESULT Original Array Works! 2 -1 2 Prefix Sum Check: prefix[0] = 2 >= 0 OK prefix[1] = 1 >= 0 OK prefix[2] = 3 >= 0 OK Output: 0 No operations needed! Key Insight: Use a Min-Heap to greedily track the smallest (most negative) elements seen so far. When prefix sum becomes negative, remove the smallest element (move it to end). This maximizes the remaining prefix sum, minimizing total operations needed. TutorialsPoint - Make the Prefix Sum Non-negative | Greedy with Min-Heap Approach
Asked in
Google 15 Amazon 12 Microsoft 8
32.0K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen