The DP table records smaller knapsack questions before using them in larger ones. Each row adds one more item, and each column fixes a capacity. The recurrence works because every item is either taken or left.

highlighted = computed this step

State definition

The state dp at i,w means best value using the first i items with capacity w. Why: each state is small enough to reuse inside later states.

dp[i,w]=best valuedp[i,w]=\text{best value}
DP state ideaThe first rows of the recomputed table show the base case and first item.first DP rows012345670000000001111111

Take or leave

For item i, the recurrence compares leaving the item with taking it if it fits. Why: every feasible subset either contains the current item or does not.

dp[i,w]=max(leave,take)dp[i,w]=\max(\text{leave},\text{take})
DP state ideaThe first rows of the recomputed table show the base case and first item.first DP rows012345670000000001111111

First item

The first item has weight 1 and value 1, so every positive capacity can earn value 1. Why: the first row already reuses the same decision rule.

dp[1,w]dp[1,w]
DP state ideaThe first rows of the recomputed table show the base case and first item.first DP rows012345670000000001111111

Diagram note

The displayed rows are copied from the recomputed DP table, not authored separately. Pixel positions are rounded for layout; every number shown is exact.

state definition drives table filling\text{state definition drives table filling}
DP state ideaThe first rows of the recomputed table show the base case and first item.first DP rows012345670000000001111111