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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code