9.3 Unbounded Knapsack / Coin Change
চিনবেন কীভাবে
items can be reused any number of times — coin change, rod cutting; loop dp forwards
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন
Demo: Coin Change — LC 322 (Medium — Amazon/Google High)
Statement (Demo): Given coins and an amount, return the fewest coins that make up the amount, or -1 if impossible.
Example: coins=[1,2,5], amount=11 → 3 (5 + 5 + 1) | ⚡ coins.length ≤ 12, amount ≤ 10⁴
Approach: dp[a] = the fewest coins for amount a. For each coin, update a going forwards — forwards means reuse is allowed (compare with the backwards loop in 9.2).
function coinChange(coins, amount) {
const dp = new Array(amount + 1).fill(Infinity);
dp[0] = 0;
for (const coin of coins)
for (
let a = coin;
a <= amount;
a++ // forwards = unbounded
)
dp[a] = Math.min(dp[a], dp[a - coin] + 1);
return dp[amount] === Infinity ? -1 : dp[amount];
}
Complexity: Time O(n · amount), Space O(amount)
Demo · Coin Changeplan · দিন ০৯৩LC 322
নোট · ফাঁকা
প্রবলেম
- Rod CuttingGfG(the profit form of unbounded knapsack)
Statement: A rod of length
nandprices[i]for a piece of lengthi+1are given. Cut the rod to maximize total value.
Example:prices=[1,5,8,9,10,17,17,20], n=8→22(lengths 2 + 6) | ⚡n ≤ 1000নোট · ফাঁকা