Intuition
Pay for the units both requirements share once at the cheapest combined rate, then cover each leftover side at the cheaper of its single price and the combined price.
Explanation
Idea
Every unit you buy falls into one of two situations: it helps both requirements at once, or it helps only one side. Serve the shared part first, then cover whatever is left.
The number of units that can help both sides simultaneously is both = min(need1, need2), because you can only "double up" as many times as the smaller requirement allows. After that, one requirement is fully met and the other still needs rem = |need1 - need2| more single-sided units.
Per-unit prices
For each kind of unit, pick the cheapest way to produce it:
- A shared unit (adds to both): buy one type-3 item (
costBoth), or buy one type-1 plus one type-2 (cost1 + cost2). Price =min(costBoth, cost1 + cost2). - A leftover type-1 unit: a type-1 item works, but a type-3 item also adds to type 1 (the extra type-2 contribution is harmless since we only need at least need2). Price =
min(cost1, costBoth). - A leftover type-2 unit: symmetrically, price =
min(cost2, costBoth).
Because each unit is independent and these are the cheapest options, multiplying price by quantity gives the optimum. No interaction between blocks can beat it.
Walk-through
Take cost1 = 3, cost2 = 2, costBoth = 1, need1 = 3, need2 = 2.
both = min(3, 2) = 2. Shared unit price =min(1, 3 + 2) = 1, so the shared block costs2 * 1 = 2.- Leftover type 1:
rem1 = 3 - 2 = 1. Unit price =min(3, 1) = 1, costing1 * 1 = 1. - Leftover type 2:
rem2 = 2 - 2 = 0, costing0. - Total =
2 + 1 + 0 = 3.
Buying three type-3 items is exactly what this adds up to, and nothing cheaper exists.
Complexity
- Time: O(1). A handful of comparisons and multiplications.
- Space: O(1)
Implementation
class Solution {
public long minimumCost(int cost1, int cost2, int costBoth, int need1, int need2) {
long both = Math.min(need1, need2);
long rem1 = (long) need1 - both;
long rem2 = (long) need2 - both;
long total = both * Math.min((long) costBoth, (long) cost1 + cost2);
total += rem1 * Math.min((long) costBoth, (long) cost1);
total += rem2 * Math.min((long) costBoth, (long) cost2);
return total;
}
}