编辑代码

//JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
function knapsack(capacity, weights, prices) {
  const n = weights.length;
  const dp = Array.from({ length: n + 1 }, () => Array.from({ length: capacity + 1 }, () => 0));
  for (let i = 1; i <= n; i++) {
    for (let j = 1; j <= capacity; j++) {
      if (j < weights[i - 1]) {
        dp[i][j] = dp[i - 1][j];
      } else {
        dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weights[i - 1]] + prices[i - 1]);
      }
    }
  }
  return dp[n][capacity];
}

const capacity = 50;
const weights = [10, 20, 30];
const prices = [60, 100, 120];
console.log(knapsack(capacity, weights, prices)); // 220