Here's the complete solution:
for i from 1 to n: for w from 0 to W: if w[i] <= w: dp[i][w] = max(dp[i-1][w], dp[i-1][w-w[i]] + v[i]) else: dp[i][w] = dp[i-1][w]
return dp[n][W]
Time: . Space: .
You can reduce space to by noticing each row only depends on the previous row. Process weights from down to to avoid overwriting values you still need. The implementation follows directly from the transition formula. Each line of code corresponds to part of the mathematical formula. Walk through a small example step by step to verify your understanding.