#2412
Hard Algorithms Minimum money required before transactions
Array Greedy Sorting
42.0% acceptance
Feb 25, 2026
415
37
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 some amount of money. In order to complete
transaction i, money >= costi must hold true. After performing a transaction,
money = 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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn minimum_money(transactions: Vec<Vec<i32>>) -> i64 {
let mut total_loss: i64 = 0;
for t in &transactions {
total_loss += (t[0] - t[1]).max(0) as i64;
}
let mut ans: i64 = 0;
for t in &transactions {
let cost = t[0] as i64;
let cashback = t[1] as i64;
let loss = (cost - cashback).max(0);
// Worst case: do this transaction last, needing total_loss - loss + cost
let worst = total_loss - loss + cost;
ans = ans.max(worst);
}
ans
}
}