lazyneuron's blog

By lazyneuron, history, 4 years ago,

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; }

• -21

 » 4 years ago, # |   0 Auto comment: topic has been updated by lazyneuron (previous revision, new revision, compare).
•  » » 4 years ago, # ^ |   0 https://m.youtube.com/watch?v=U4O3SwDamA4 this video might help you understand..
•  » » » 4 years ago, # ^ |   -17 This video is too long. If I can get a few lines of explanation, that would be awesome.
•  » » » » 4 years ago, # ^ |   0 since you dont really like long and boring videos , this might helpVideoP.S. :- I am sorry
•  » » » » » 4 years ago, # ^ |   +3 haha funny one ..
 » 4 years ago, # | ← Rev. 2 →   +8 I don't think this code is correct. Maybe it should bedp[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 iteration i is maximum possible value with weight j using only the first i items.