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 ofmoneyrequired before any transaction so that all of the transactions can be completedregardless of the order of the transactions.
Input: transactions =[[2,1],[5,0],[4,2]]Output: 10Explanation: Starting with money =10, the transactions can be performed in any order.It can be shown that starting with money <10 will fail to complete all transactions in some order.
Input: transactions =[[3,0],[0,3]]Output: 3Explanation:
- If transactions are in the order [[3,0],[0,3]], the minimum money required to complete the transactions is3.- If transactions are in the order [[0,3],[3,0]], the minimum money required to complete the transactions is0.Thus, starting with money =3, the transactions can be performed in any order.
Transactions where cost > cashback are risky, as they always reduce your money. To guarantee all orders work, you must have enough money to cover the worst-case order: do all risky transactions first, then the rest. The minimum required is the sum of all risky costs minus their cashback, plus the maximum cost among all transactions.
classSolution {
publiclongminimumMoney(int[][] transactions) {
long risky = 0, ans = 0;
for (int[] t : transactions) {
if (t[0]> t[1]) risky += t[0]- t[1];
}
for (int[] t : transactions) {
ans = Math.max(ans, risky + t[0]);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funminimumMoney(transactions: Array<IntArray>): Long {
var risky = 0Lfor (t in transactions) {
if (t[0] > t[1]) risky += t[0] - t[1]
}
var ans = 0Lfor (t in transactions) {
ans = maxOf(ans, risky + t[0].toLong())
}
return ans
}
}
1
2
3
4
5
6
defminimum_money(transactions: list[list[int]]) -> int:
risky =0for cost, cashback in transactions:
if cost > cashback:
risky += cost - cashback
return max(risky + cost for cost, cashback in transactions)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnminimum_money(transactions: Vec<Vec<i32>>) -> i64 {
letmut risky =0i64;
for t in&transactions {
if t[0] > t[1] {
risky += (t[0] - t[1]) asi64;
}
}
letmut ans =0i64;
for t in&transactions {
ans = ans.max(risky + t[0] asi64);
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
minimumMoney(transactions: number[][]):number {
letrisky=0;
for (const [cost, cashback] oftransactions) {
if (cost>cashback) risky+=cost-cashback;
}
letans=0;
for (const [cost] oftransactions) {
ans= Math.max(ans, risky+cost);
}
returnans;
}
}