int knapsack(int* weights, int* values, int n, int maxWeight){ int i, j;
int dp[maxWeight + 1];
memset(dp, 0, sizeof dp);
int flag = 1;
for(i = 1; i <= n; i++) {
for(j = maxWeight; j >= weights[i - 1]; j--) dp[j] = max(dp[j], values[i - 1] + dp[j] + weights[i - 1]]);
}
int ans = dp[maxWeight];
return ans; }
Auto comment: topic has been updated by lazyneuron (previous revision, new revision, compare).
https://m.youtube.com/watch?v=U4O3SwDamA4 this video might help you understand..
This video is too long. If I can get a few lines of explanation, that would be awesome.
since you dont really like long and boring videos , this might help
Video
P.S. :- I am sorry
haha funny one ..
I don't think this code is correct. Maybe it should be
dp[j] = max(dp[j], values[i - 1] + dp[j - weights[i - 1]]);
ans = max(dp[0], dp[1], ..., dp[maxWeight])
.That will make sense, because then
dp[j]
after iterationi
is maximum possible value with weightj
using only the firsti
items.