Make the Prefix Sum Non-negative - Problem
Make the Prefix Sum Non-negative

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
Water TankCurrent: +3 units+5Add Water-7Drain (Delay!)+4Add WaterDelayed OperationsQueue: [-7] โ†’ 1 operation
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!
Asked in
Google 45 Amazon 38 Meta 28 Microsoft 22
43.7K Views
Medium-High Frequency
~25 min Avg. Time
1.8K 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