3789 - Minimum Cost to Acquire Required Items (Medium)
Problem Link
https://leetcode.com/problems/minimum-cost-to-acquire-required-items
Problem Statement
You are given five integers , , , , and .
There are three types of items available:
- An item of type 1 costs and contributes 1 unit to the type 1 requirement only.
- An item of type 2 costs and contributes 1 unit to the type 2 requirement only.
- An item of type 3 costs and contributes 1 unit to both type 1 and type 2 requirements.
You must collect enough items so that the total contribution toward type 1 is at least and the total contribution toward type 2 is at least .
Return an integer representing the minimum possible total cost to achieve these requirements.
Example 1:
Input: , , , ,
Output: 3
Explanation:
After buying three type 3 items, which cost , the total contribution to type 1 is 3 () and to type 2 is 3 (). Any other valid combination would cost more, so the minimum total cost is 3.
Example 2:
Input: , , , ,
Output: 22
Explanation:
We buy items of type 1 and items of type 2: . Any other valid combination would cost more, so the minimum total cost is 22.
Example 3:
Input: , , , ,
Output: 0
Explanation:
Since no items are required (), we buy nothing and pay 0.
Constraints:
Approach 1: Greedy
Let and . Suppose we buy type 3 items and fill any remaining requirements with single-type items. How does the total cost change if we buy one more type 3 item?
- For , both requirements still need units. One more type 3 item replaces one item of each single type, so the total cost changes by .
- For , only the larger requirement still needs units. One more type 3 item replaces one single-type item for that requirement. It can still save money because exceeding the smaller requirement is allowed.
- Once , both requirements are met. Each additional item only increases the cost.
Within each of the first two ranges, every replacement changes the cost by the same amount, so a minimum occurs at an endpoint. The three expressions in the code evaluate those endpoints in order: buy only single-type items (), cover the shared units with type 3 items and buy the rest individually (), or cover both requirements entirely with type 3 items (). Return the smallest of these costs.
The time complexity is and the space complexity is .
class Solution:
def minimumCost(self, cost1: int, cost2: int, costBoth: int, need1: int, need2: int) -> int:
mi = min(need1, need2)
mx = max(need1, need2)
return min(
need1 * cost1 + need2 * cost2,
mi * costBoth + (need1 - mi) * cost1 + (need2 - mi) * cost2,
mx * costBoth
)3736 - Minimum Moves to Equal Array Elements III
Minimize unit increments to equalize an array by summing each element's distance to the current maximum.
3841 - Palindromic Path Queries in a Tree
Answer tree-path palindrome rearrangement queries under label updates using parity masks, heavy-light decomposition, and a Fenwick tree.