An interactive visualization of the classic 0/1 Knapsack dynamic programming algorithm. Watch the 2D DP table fill as we decide whether to take or skip each item to maximize value within a weight capacity.
Dynamic Programming Classic Mediumn items, each with a weight and a value, and a knapsack with a maximum weight capacity W, find the maximum value that can be carried in the knapsack.[2, 3, 4, 5] and values [3, 4, 5, 6], capacity W=8.fun knapsack(weights: IntArray, values: IntArray, capacity: Int): Int { val n = weights.size val dp = Array(n + 1) { IntArray(capacity + 1) } for (i in 1..n) { for (w in 0..capacity) { dp[i][w] = dp[i - 1][w] // skip item if (weights[i - 1] <= w) { dp[i][w] = maxOf( dp[i][w], dp[i - 1][w - weights[i - 1]] + values[i - 1] ) } } } return dp[n][capacity]}
dp[i][w] = maximum value achievable using the first i items with capacity w.
For each item i and capacity w, we have two choices:
dp[i][w] = dp[i-1][w] (inherit value from previous row)dp[i][w] = dp[i-1][w - weight[i-1]] + value[i-1] (if weight[i-1] โค w)
We take the maximum of these two options. The base case is dp[0][w] = 0 (no items = zero value).
(n+1) ร (capacity+1), filled with zeros.i (1 to n) and each weight w (0 to capacity):
weight[i-1] โค w), calculate the value of taking it.dp[n][capacity] holds the maximum value.
Where n is the number of items and W is the knapsack capacity. This is pseudopolynomial time because it depends on the numeric value of W, not its input size (log W). The space can be optimized to O(W) using a 1D rolling array, but the 2D version is clearer for visualization.