Ctrl K

Postpone Payments to Stay Solvent

Medium
The array flows lists money movements on an account in order: a positive number is income, a negative one is a charge. The account starts at zero, and after every movement the balance must not be negative. In one operation you may take any movement and move it to the very end of the list. What is the smallest number of operations that keeps the balance from ever going below zero? The total of all movements is guaranteed to be non-negative, so this is always possible.
Example 1
flows=[5, -2, 4, -1] → 0

The running balance is 5, 3, 7, 6 and never dips below zero, so nothing needs to move.

Example 2
flows=[2, -6, 1, 5] → 1

After −6 the balance is −4. Moving −6 to the end gives [2, 1, 5, −6] with balances 2, 3, 8, 2.

Example 3
flows=[-3, -1, 2, 4] → 2

Both expenses come before any income, so both must move: [2, 4, −3, −1].

Constraints
  • 1 ≤ len(flows) ≤ 10⁵
  • -10⁹ ≤ flows[i] ≤ 10⁹
  • sum(flows) ≥ 0
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsStudios for Recording Sessions MediumJobs With a Cooldown MediumSorted Into Runs of Three MediumSpread Out the Labels MediumSplicing Ropes Medium
loading Python…
Input
flows=[5, -2, 4, -1]
Expected
0

Run checks the first 3 tests in your browser. Submit checks all 89 tests on the server, hidden ones included.