FastPrepDefer Expenses to Preserve Balance

Defer Expenses to Preserve Balance

DRW logoDRW● MediumINTERNPHONE SCREEN
Learn

Problem statement

You are given a chronological array transactions. Positive values are income and negative values are expenses. The running balance must never become negative.

You may defer an expense by removing it from its current position and appending it after every non-deferred transaction. Deferred expenses retain their relative order. Return the minimum number of expenses that must be deferred.

Function

minimumDeferredExpenses(transactions: int[]) → int

Examples

Example 1

transactions = [4,-5,3,-2,1]return = 1

Defer -5; the order [4,3,-2,1,-5] never has a negative prefix.

Example 2

transactions = [10,-4,-8,7,-6,5]return = 1

Deferring -8 is sufficient.

Example 3

transactions = [3,-1,-2,4]return = 0

Every original prefix already has a nonnegative balance.

Constraints

  • 1 <= transactions.length <= 100000
  • -1000000000 <= transactions[i] <= 1000000000
  • The total sum of transactions is nonnegative.

More DRW problems

See DRW hiring insights
public int minimumDeferredExpenses(int[] transactions) {
    // Write your code here.
}
transactions[4,-5,3,-2,1]
expected1
Checking account…