AlgoTales · Roadmap

Unbounded Knapsack

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Unbounded knapsack is the same idea as the knapsack, except every item may be used as many times as you like. The best value for a given capacity is found by trying each item as the last one added. It covers rod cutting, coin problems and any "unlimited supply" choice.

Practical use cases

  • Web app: Bakery or catering pack planner. A catering site sells trays of three sizes, and each size has a price. For an order needing 20 portions, the page works out the combination of trays that gives the best price or fewest wasted portions, allowing repeats of the same tray. The kitchen sees the exact tray mix.
  • Web app: Cloud plan or credit bundle picker. A SaaS billing page offers credit packs of 100, 500 and 1,200 credits with different prices. A customer needing 1,700 credits sees the cheapest mix of packs, with repeats allowed. The tool builds answers for 0 up to 1,700 in one pass. If the customer changes the amount, the same table already holds the answer for every smaller amount.
  • System: Rod cutting and packaging. A factory cuts a steel rod into pieces to sell for the highest total, and a packing line chooses box sizes. Pieces may repeat, so it is the unlimited version. In each of these, the same size can be used again and again, so the table for the remaining space is reused for every choice and answers come from simple lookups.

The story: The Bakery with Endless Trays

Mrs. Joshi runs a tiny bakery with an oven of size 8. She bakes two kinds of trays: a small tray (it takes 2 units of oven space and earns ₹3) and a big tray (3 units of space, ₹5). Flour is never a problem, so she can bake as many small and big trays as she likes. How should she fill the oven for the best profit?

Mira remembered the trek bag, where each item was available once. "This is different. Here an item can be used again and again." In the bag puzzle, every item got a new row because you could not reuse it. Here, no rows are needed: one row of boxes, one box per oven size.

For an oven of size c, ask: "What was the last tray I put in?" If it was the big tray, the rest of the oven (size c − 3) was filled in the best possible way, which is already written in an earlier box, and it may well contain big trays too! So best[c] = max over trays (tray profit + best[c − tray size]).

This is unbounded knapsack: like 0/1 knapsack, but with an unlimited supply of every item. The table fills left to right, and "reusing an item" simply means reading boxes that are already filled with answers that might use that same item.

How to spot this problem, and where you need it

You have item types with a size and a value, you can use each type as often as you like, and you want the best total for a fixed size or budget.

Signs you need it

  • The problem says "unlimited supply", "any number of times" or "infinite coins".
  • It asks for the best value or fewest items to fill an exact capacity.
  • Greedy picking of the best value-per-size item leaves awkward leftover space and gives a worse total.

Where to use it in a project

  • Credit, data or storage pack selection on SaaS billing pages.
  • Cutting, packaging or portion planning tools where the same size can be used repeatedly.

The solution

Make a table where entry c is the best value for capacity c, starting with 0 for capacity 0. For each capacity from 1 up to the limit, try every item that fits: take its value plus the table entry for the remaining capacity, which is already filled. Keep the best result. Because items can repeat, the remaining space may use the same item again, which the table handles naturally. The last entry is your answer.

Payoff: Before: trying every combination of packs, millions for a big order. After: one table of 1,700 entries filled in a blink.

Explain it like I am 8

Imagine unlimited bricks of two sizes and a box of a fixed size. To fill a box of size 8, you put one brick in and ask "what is the best way to fill the leftover space?" That leftover is a smaller box you already solved. You try each kind of brick as the last one and keep the best.

How it works, step by step

  1. State: dp[c] = the best total value for a bag of size c, with unlimited copies of every item.
  2. Base case: dp[0] = 0 (a bag of size 0 holds nothing).
  3. Transition: dp[c] = max over items that fit (dp[c - w] + v). If no item fits, dp[c] = 0.
  4. Fill from small to large. Because dp[c - w] already allows the same item again, repeats are automatic.
  5. Compare with 0/1: in 0/1 the size loop goes from big to small (so an item isn't reused); in unbounded it goes small to big.

The code in four languages

PHP

<?php
// Unbounded knapsack: every item can be used any number of times.
// dp[c] = best value for a bag of size c.
function unboundedKnapsack(array $weights, array $values, int $cap): int {
    $dp = array_fill(0, $cap + 1, 0);            // dp[0] = 0: nothing fits in size 0
    for ($c = 1; $c <= $cap; $c++) {             // small to large: allows reuse of items
        foreach ($weights as $i => $w) {
            if ($w <= $c) {
                $dp[$c] = max($dp[$c], $dp[$c - $w] + $values[$i]);
            }
        }
    }
    return $dp[$cap];
}

echo unboundedKnapsack([2, 3], [3, 5], 8), "\n";    // 13 (3 + 3 + 2 space, 5 + 5 + 3 profit)
echo unboundedKnapsack([5], [10], 4), "\n";         // 0  (nothing fits)

JavaScript

// Unbounded knapsack: every item can be used any number of times.
// dp[c] = best value for a bag of size c.
function unboundedKnapsack(weights, values, cap) {
  const dp = new Array(cap + 1).fill(0);         // dp[0] = 0: nothing fits in size 0
  for (let c = 1; c <= cap; c++) {               // small to large: allows reuse of items
    for (let i = 0; i < weights.length; i++) {
      if (weights[i] <= c) {
        dp[c] = Math.max(dp[c], dp[c - weights[i]] + values[i]);
      }
    }
  }
  return dp[cap];
}

console.log(unboundedKnapsack([2, 3], [3, 5], 8));    // 13 (3 + 3 + 2 space, 5 + 5 + 3 profit)
console.log(unboundedKnapsack([5], [10], 4));         // 0  (nothing fits)

Java

public class Main {
    // Unbounded knapsack: every item can be used any number of times.
    // dp[c] = best value for a bag of size c.
    static int unboundedKnapsack(int[] weights, int[] values, int cap) {
        int[] dp = new int[cap + 1];                 // dp[0] = 0: nothing fits in size 0
        for (int c = 1; c <= cap; c++) {             // small to large: allows reuse of items
            for (int i = 0; i < weights.length; i++) {
                if (weights[i] <= c) {
                    dp[c] = Math.max(dp[c], dp[c - weights[i]] + values[i]);
                }
            }
        }
        return dp[cap];
    }

    public static void main(String[] args) {
        System.out.println(unboundedKnapsack(new int[]{2, 3}, new int[]{3, 5}, 8));   // 13 (3 + 3 + 2 space, 5 + 5 + 3 profit)
        System.out.println(unboundedKnapsack(new int[]{5}, new int[]{10}, 4));        // 0  (nothing fits)
    }
}

Go

package main

import "fmt"

// Unbounded knapsack: every item can be used any number of times.
// dp[c] = best value for a bag of size c.
func unboundedKnapsack(weights, values []int, cap int) int {
	dp := make([]int, cap+1)    // dp[0] = 0: nothing fits in size 0
	for c := 1; c <= cap; c++ { // small to large: allows reuse of items
		for i, w := range weights {
			if w <= c {
				dp[c] = max(dp[c], dp[c-w]+values[i])
			}
		}
	}
	return dp[cap]
}

func main() {
	fmt.Println(unboundedKnapsack([]int{2, 3}, []int{3, 5}, 8)) // 13 (3 + 3 + 2 space, 5 + 5 + 3 profit)
	fmt.Println(unboundedKnapsack([]int{5}, []int{10}, 4))      // 0  (nothing fits)
}

Time: O(W × n) · Extra space: O(W). One box per bag size, and each looks at every item once. W is the bag size and n the number of item kinds.

Watch out for

  • Using the 0/1 style (big-to-small loop or a row per item) and then wondering why repeats are not allowed.
  • Reusing an item that does not fit: always check w <= c first.
  • Thinking dp[c] must fill the bag exactly. Here leftover space is allowed (profit just stays lower); "exactly c" problems use an impossible marker instead.

Quick check

  1. What is the key difference from 0/1 knapsack?
    • Items can be used unlimited times
    • The bag is bigger
    • Values are negative
  2. In the bakery, what is the best profit for an oven of size 6?
    • 9
    • 10
    • 12
  3. How is dp[c] built?
    • Add all earlier boxes together
    • Take the best of (dp[c - w] + v) over the items that fit
    • Copy dp[c - 1]