I just came across this code snippet of 0-1 knapsack

```
int knapsack_01(int *val, int *wt, int n, int W)
{
int dp[W+1];
fill(dp, dp + W +1, 0);
for(int i = 0; i < n; i++)
for(int j = W; j >= 0; j--) //why this loop needs to iterate in reverse order?
if(wt[i] <= j && dp[j] < dp[j - wt[i]] + val[i])
dp[j] = dp[j - wt[i] + val[i];
return dp[W];
}
```

and could not understand why the second loop involving ‘j’ has to run in reverse order to get the answer correct?

**I get WA for 0-1 knapsack if I iterate j from 0 to W**

NOTE: both the arrays ‘val’ and ‘wt’ are 0-based indexed.

someone please help…