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
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.
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
Understanding the Visualization
1
Input
Array with potentially problematic negative values
2
Process
Move negative elements to end when prefix sum goes negative
3
Output
Minimum number of operations needed
Key Takeaway
🎯 Key Insight: When prefix sum becomes negative, greedily move the smallest element seen so far to the end
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code