self-explanatory with the code logic?
there are three things you can buy: a type 1 item, a type 2 item, or one item that counts as both.
- the first
min(need1, need2)units are needed by both types, so each one costs the cheaper ofcostBothandcost1 + cost2 - the leftover units are only needed by one type, so each one costs the cheaper of that type's own cost and
costBoth
code link to code
class Solution {
public:
long long minimumCost(int cost1, int cost2, int costBoth, int need1, int need2) {
long long ans{};
long long bothNeed{min(need1, need2)};
ans += bothNeed * min(costBoth, cost1 + cost2);
if (need1 > bothNeed) {
ans += (static_cast<long long>(need1) - bothNeed) * min(cost1, costBoth);
} else if (need2 > bothNeed) {
ans += (static_cast<long long>(need2) - bothNeed) * min(cost2, costBoth);
}
return ans;
}
};complexity link to complexity
- Time:
O(1)- Space:
O(1)
time taken link to time taken
- 5 minutes and 11 seconds