Make the Prefix Sum Non-negative - Problem
Make the Prefix Sum Non-negative
You're given a
๐ What's a prefix sum? The prefix sum at index
๐ Available Operation: Pick any element from
๐ฏ Goal: Find the minimum number of operations needed to ensure that no prefix sum in the resulting array is negative.
Example: If
You're given a
0-indexed integer array nums that may contain both positive and negative numbers. Your goal is to rearrange the array by moving elements to the end so that all prefix sums become non-negative.๐ What's a prefix sum? The prefix sum at index
i is the sum of all elements from index 0 to i (inclusive).๐ Available Operation: Pick any element from
nums and move it to the end of the array. You can perform this operation any number of times.๐ฏ Goal: Find the minimum number of operations needed to ensure that no prefix sum in the resulting array is negative.
Example: If
nums = [2, -3, 1], the initial prefix sums are [2, -1, 0]. Since the second prefix sum is negative, we need to rearrange the array! Input & Output
example_1.py โ Basic Case
$
Input:
[2, 3, -5, 4]
โบ
Output:
0
๐ก Note:
The prefix sums are [2, 5, 0, 4]. All prefix sums are non-negative, so no operations are needed.
example_2.py โ Need Rearrangement
$
Input:
[3, -5, 4]
โบ
Output:
1
๐ก Note:
Initial prefix sums: [3, -2, 2]. The second prefix sum is negative. Move -5 to end: [3, 4, -5] gives prefix sums [3, 7, 2]. One operation needed.
example_3.py โ Multiple Negatives
$
Input:
[1, -3, 2, -4, 5]
โบ
Output:
2
๐ก Note:
Initial prefix sums: [1, -2, 0, -4, 1]. Both -3 and -4 cause negative prefix sums. We need to move both to the end, requiring 2 operations.
Constraints
- 1 โค nums.length โค 105
- -109 โค nums[i] โค 109
- It is guaranteed that a solution exists (sum of all elements โฅ 0)
Visualization
Tap to expand
Understanding the Visualization
1
Monitor Water Level
Keep track of current water level (running sum)
2
Queue Drain Operations
When we encounter drains (negatives), remember them
3
Delay Largest Drains
If water level goes negative, delay the biggest drain until later
4
Count Delays
Number of delayed operations is our answer
Key Takeaway
๐ฏ Key Insight: Only delay operations that would cause the water level to go negative, and always delay the most negative ones first!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code