KatInterview

Minimum Postponed Debits to Avoid Negative Balance

Heaps, Sorting & SearchAuto-graded · 24 test cases
EasyAuto-gradedHeaps, Sorting & Searchheaps-sortinggreedy-intervalsarrays

Last updated

Find the minimum number of negative transactions to postpone so that the running account balance remains non-negative throughout processing.

You are given a chronological sequence of financial transactions represented by an array of integers a. Positive integers represent credits (deposits), negative integers represent debits (withdrawals), and zero values represent neutral entries.

Starting with an initial balance of 0, transactions are processed sequentially. The balance must never drop below 0 after any transaction. To ensure the account balance remains non-negative at all times, you are permitted to postpone certain debit transactions by moving them to the end of the sequence. Postponed transactions will be executed at the very end after all other transactions have been processed.

Return the minimum number of debit transactions that need to be postponed.

Rules

  • Only negative values (debits) may be postponed. Neutral values (0) do not affect the balance and do not need to be postponed.
  • Non-postponed transactions are processed in their original relative order.
  • Postponed debits are executed after all remaining transactions. The overall sum of all elements in a is guaranteed to be non-negative ($\sum a_i \ge 0$), ensuring that the final sequence will be valid once all debits are paid.
  • A running balance of exactly 0 is allowed at any point.

Constraints

  • $1 \le \text{len}(a) \le 10^5$
  • $-10^9 \le a[i] \le 10^9$
  • $\sum a[i] \ge 0$

Examples

Example 1

Input: min_expenses_to_move([5, -3, -4, 6, -1])

Output: 1

Example 2

Input: min_expenses_to_move([-2, 3, -1, -5, 4, 2])

Output: 2

Example 3

Input: min_expenses_to_move([3, -1, -2, 4])

Output: 0

Hints

Hint 1

Process transactions sequentially while tracking the running balance.

Hint 2

Maintain a priority queue (min-heap) of all debit amounts encountered so far that have not been postponed.

Hint 3

When the running balance falls below 0, which debit should be postponed to regain the largest balance with a single move?