[LeetCode] Minimum Money Required Before Transactions

2412. Minimum Money Required Before Transactions

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
long long minimumMoney(vector<vector<int>>& transactions) {
long long res = 0, over = 0;
vector<vector<long long>> A;
for(auto& t : transactions) {
long long c = t[0], b = t[1];
if(b < c) A.push_back({c,b});
else if(c <= b) over = max(over, c);
}
sort(begin(A), end(A), [](auto a, auto b) {
return a[1] == b[1] ? a[0] > b[0] : a[1] < b[1];
});
long long req = 0, ma = 0;
for(auto& v : A) {
long long c = v[0], b = v[1];
req += c;
res = max(res, req);
req -= b;
ma = max(ma, c);
}
return max({res, ma, req + over});
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/18/PS/LeetCode/minimum-money-required-before-transactions/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.