Dynamic Programming21 sections · 916 units
Open in Course

Knapsack 2 - State Design

Value as index

Define dp[i][v]dp[i][v] as the minimum weight needed to achieve exactly value vv using items 11 to ii. Here ii ranges from 00 to nn, and vv ranges from 00 to VmaxV_{max} where Vmax=viV_{max} = \sum v_i.

Base cases:

1.1. dp[0][0]=0dp[0][0] = 0 (zero items, zero value, zero weight needed)

2.2. dp[0][v]=dp[0][v] = \infty for v>0v > 0 (impossible to get positive value with no items)

The transition mirrors the original knapsack. For each item ii, you either skip it and keep dp[i1][v]dp[i-1][v], or include it and check dp[i1][vvi]+widp[i-1][v - v_i] + w_i. You take the minimum of the two.