LeetCode-in-Java

2412. Minimum Money Required Before Transactions

Hard

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.

Example 1:

Input: transactions = [[2,1],[5,0],[4,2]]

Output: 10

Explanation:

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.

Example 2:

Input: transactions = [[3,0],[0,3]]

Output: 3

Explanation:

Thus, starting with money = 3, the transactions can be performed in any order.

Constraints:

Solution

public class Solution {
    public long minimumMoney(int[][] transactions) {
        int max = 0;
        long sum = 0;
        for (int[] transaction : transactions) {
            int diff = transaction[1] - transaction[0];
            if (diff < 0) {
                sum -= diff;
                transaction[0] += diff;
            }
            max = Math.max(max, transaction[0]);
        }
        return max + sum;
    }
}