#2412
Minimum Money Required Before Transactions
HardArrayGreedySortingGreedy AlgorithmsSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n log n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal approach involves separating transactions into two categories based on cashback. By sorting and calculating the minimum required money efficiently, we can ensure all transactions can be completed regardless of order.
⚙️
Algorithm
3 steps- 1Step 1: Split transactions into two lists: one for transactions with cashback >= cost and another for those with cashback < cost.
- 2Step 2: For the first list, sort transactions by cost in descending order.
- 3Step 3: Calculate the minimum starting money required by iterating through both lists, adjusting the current money and tracking the maximum money needed.
solution.py26 lines
1# Full working Python code
2def min_money_optimal(transactions):
3 high_cashback = []
4 low_cashback = []
5 for cost, cashback in transactions:
6 if cashback >= cost:
7 high_cashback.append((cost, cashback))
8 else:
9 low_cashback.append((cost, cashback))
10
11 # Sort high cashback transactions by cost descending
12 high_cashback.sort(reverse=True, key=lambda x: x[0])
13 current_money = 0
14 min_money_needed = 0
15
16 # Process high cashback transactions
17 for cost, cashback in high_cashback:
18 current_money += cashback - cost
19 min_money_needed = max(min_money_needed, cost - current_money)
20
21 # Process low cashback transactions
22 for cost, cashback in low_cashback:
23 current_money += cashback - cost
24 min_money_needed = max(min_money_needed, cost - current_money)
25
26 return min_money_neededℹ
Complexity note: The complexity is dominated by the sorting step for the high cashback transactions, making it efficient for large inputs.
- 1Transactions with cashback >= cost can be beneficial and should be prioritized.
- 2Sorting helps in managing the order of transactions to minimize the required starting money.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.