Minimum Money Required Before Transactions — LeetCode 2412 Python Solution
- Problem
- #2412
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- transactions = [[2,1],[5,0],[4,2]]
- Output
- 10
- Explanation
- Starting with money = 10, the transactions can be performed in any order.
Python solution
class Solution:
def minimumMoney(self, transactions: List[List[int]]) -> int:
s = sum(max(0, a - b) for a, b in transactions)
ans = 0
for a, b in transactions:
if a > b:
ans = max(ans, s + b)
else:
ans = max(ans, s + a)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the number of transactions |
| Space | O(1) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2412. Minimum Money Required Before Transactions is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2412. Minimum Money Required Before Transactions?
- LeetCode 2412. Minimum Money Required Before Transactions is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2412. Minimum Money Required Before Transactions?
- The Python solution on this page runs in O(n), where n is the number of transactions.
- What is the space complexity of LeetCode 2412. Minimum Money Required Before Transactions?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2412. Minimum Money Required Before Transactions cover?
- LeetCode 2412. Minimum Money Required Before Transactions is tagged Greedy, Array and Sorting on LeetCode.