#3789
Minimum Cost to Acquire Required Items
MediumMathGreedyGreedyDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
Use a greedy approach to minimize costs by prioritizing the cheapest item options based on needs.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the maximum number of type 3 items to buy, which is min(need1, need2).
- 2Step 2: Determine remaining needs for type 1 and type 2 after buying type 3 items.
- 3Step 3: Use the cheaper option between type 1 and type 2 items for remaining needs.
solution.py6 lines
1def minCost(cost1, cost2, costBoth, need1, need2):
2 type3 = min(need1, need2)
3 remaining1 = need1 - type3
4 remaining2 = need2 - type3
5 total_cost = type3 * costBoth + max(0, remaining1) * min(cost1, costBoth) + max(0, remaining2) * min(cost2, costBoth)
6 return total_costℹ
Complexity note: This solution runs in constant time since it only involves a few arithmetic operations.
- 1Using type 3 items can significantly reduce costs.
- 2Always compare the cost of individual items with the combined item.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.