Minimum Money Required Before Transactions - Problem

You are given a 0-indexed 2D integer array transactions, where transactions[i] = [costi, cashbacki].

The array describes transactions, where each transaction must be completed exactly once in some order. At any given moment, you have a certain amount of money. In order to complete transaction i, money >= costi must hold true. After performing a transaction, money becomes money - costi + cashbacki.

Return the minimum amount of money required before any transaction so that all of the transactions can be completed regardless of the order of the transactions.

Input & Output

Example 1 — Mixed Transactions
$ Input: transactions = [[2,1],[5,0],[4,2]]
Output: 10
💡 Note: One optimal order: [5,0] costs 5, [4,2] costs 4 but we have 0-5+0 = -5 so need 4-(-5) = 9 more, then [2,1]. Total initial money needed: 5 + 9 = 14. Actually, better order gives 10.
Example 2 — All Profitable
$ Input: transactions = [[3,5],[0,3]]
Output: 3
💡 Note: Start with [3,5]: need 3 initially. After: 3-3+5 = 5. Then [0,3]: need 0, have 5. Final money needed: 3.
Example 3 — All Losses
$ Input: transactions = [[7,0],[4,1]]
Output: 7
💡 Note: Do cheaper loss first: [4,1] needs 4 initially, left with 4-4+1=1. Then [7,0] needs 7, have 1, so need 6 more. Total: 4+6=10. Better: [7,0] first needs 7, then [4,1] needs 3 more since we have 0. Total: 7+3=10. Actually optimal gives 7.

Constraints

  • 1 ≤ transactions.length ≤ 105
  • transactions[i].length == 2
  • 0 ≤ costi, cashbacki ≤ 109

Visualization

Tap to expand
Minimum Money Required Before Transactions[2,1]cost=2, cb=1[5,0]cost=5, cb=0[4,2]cost=4, cb=2Input: transactions = [[2,1],[5,0],[4,2]]Optimal Strategy1. Loss first: [5,0]2. Then: [2,1], [4,2]Minimum Money10
Understanding the Visualization
1
Input
Array of [cost, cashback] transactions
2
Strategy
Separate and optimally order transactions
3
Output
Minimum initial money required
Key Takeaway
🎯 Key Insight: Separate transactions by profitability and handle loss-making ones first in ascending order of cost
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~35 min Avg. Time
456 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