lazyneuron's blog

By lazyneuron, history, 6 years ago, In English

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

  • Vote: I like it
  • -21
  • Vote: I do not like it

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by lazyneuron (previous revision, new revision, compare).

»
6 years ago, # |
Rev. 2   Vote: I like it +8 Vote: I do not like it

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 iteration i is maximum possible value with weight j using only the first i items.