This "Hard" difficulty problem involves a sequence of transactions. Each transaction is defined by [cost, cashback]. You must have at least cost money to perform the transaction. After the transaction, your money becomes money - cost + cashback.
The goal is to find the minimum initial money you need to have to guarantee that you can complete all transactions in any possible order. This means you must prepare for the worst-case scenario.
Amazon uses this problem to test Greedy logic and Worst-case analysis. It’s tricky because you aren't choosing the order; the order is chosen "against" you. You need to find the "safest" starting amount. Interviewer's look for:
cost > cashback) and those that don't.The pattern is Greedy Worst-Case Analysis.
cost > cashback) contribute to the maximum money "dip." The total money lost from all such transactions is a key component.cost, but it also leaves you with cashback. The amount you "lose" forever is cost - cashback.Total Loss of all losing transactions + Max(Remaining needed for any single transaction).i is the cashback[i] (because you already accounted for the cost - cashback in the total loss). For a winning transaction, it's just the cost.Transactions: [[2, 1], [5, 0], [4, 8]]
[2, 1]: Losing. Loss = 1.[5, 0]: Losing. Loss = 5.[4, 8]: Winning. No loss.
Total Loss = .Worst case:
If we do [2, 1] then [5, 0] then [4, 8]:
[2, 1], we need 2. Money becomes 1.[5, 0], we need 5. We have 1. Need 4 more. Starting = . Money becomes 1.[4, 8], we need 4. We have 1. Need 3 more. Starting = .
If we did them in a different order, we might need less, but we need 10 to cover all orders.cost can still require a high starting amount.In "any order" problems, focus on the "worst order." Usually, this means doing the most "harmful" things (losing money) first and the "least harmful" things (earning money) last.