মূল কনটেন্টে যান
🌍
গ্লোবাল DSA
প্যাটার্নটপিক 9 · Dynamic Programming

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 ChangeLC 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=113 (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)

নোট · ফাঁকা

প্রবলেম

  • Rod CuttingGfG
    (the profit form of unbounded knapsack)

    Statement: A rod of length n and prices[i] for a piece of length i+1 are given. Cut the rod to maximize total value.
    Example: prices=[1,5,8,9,10,17,17,20], n=822 (lengths 2 + 6) | ⚡ n ≤ 1000

    নোট · ফাঁকা