Defer Expenses to Preserve Balance
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[]) → intExamples
Example 1
transactions = [4,-5,3,-2,1]return = 1Defer -5; the order [4,3,-2,1,-5] never has a negative prefix.
Example 2
transactions = [10,-4,-8,7,-6,5]return = 1Deferring -8 is sufficient.
Example 3
transactions = [3,-1,-2,4]return = 0Every original prefix already has a nonnegative balance.
Constraints
1 <= transactions.length <= 100000-1000000000 <= transactions[i] <= 1000000000- The total sum of
transactionsis nonnegative.