Files
hello-algo/en/codes/javascript/chapter_dynamic_programming/unbounded_knapsack.js
Yudong Jin 14c314c08c Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese

* Polish three English explanations after reader-focused review
2026-10-31 03:35:51 +08:00

64 lines
2.0 KiB
JavaScript

/**
* File: unbounded_knapsack.js
* Created Time: 2023-08-23
* Author: Gaofer Chou (gaofer-chou@qq.com)
*/
/* Unbounded knapsack: dynamic programming */
function unboundedKnapsackDP(wgt, val, cap) {
const n = wgt.length;
// Initialize the dp table
const dp = Array.from({ length: n + 1 }, () =>
Array.from({ length: cap + 1 }, () => 0)
);
// State transitions
for (let i = 1; i <= n; i++) {
for (let c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[i][c] = dp[i - 1][c];
} else {
// Take the larger value obtained by excluding and including item i
dp[i][c] = Math.max(
dp[i - 1][c],
dp[i][c - wgt[i - 1]] + val[i - 1]
);
}
}
}
return dp[n][cap];
}
/* Unbounded knapsack: space-optimized dynamic programming */
function unboundedKnapsackDPComp(wgt, val, cap) {
const n = wgt.length;
// Initialize the dp table
const dp = Array.from({ length: cap + 1 }, () => 0);
// State transitions
for (let i = 1; i <= n; i++) {
for (let c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[c] = dp[c];
} else {
// Take the larger value obtained by excluding and including item i
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[cap];
}
/* Driver code */
const wgt = [1, 2, 3];
const val = [5, 11, 15];
const cap = 4;
// Dynamic programming
let res = unboundedKnapsackDP(wgt, val, cap);
console.log(`Maximum item value within the knapsack capacity: ${res}`);
// Space-optimized dynamic programming
res = unboundedKnapsackDPComp(wgt, val, cap);
console.log(`Maximum item value within the knapsack capacity: ${res}`);