Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions patterns/dynamic-programming/0-1knapsack/first-approach.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// wrong
const knapsack = (profits, weights, capacity) => {
let result = [0, 0];
let mp = 0;
Expand Down
25 changes: 25 additions & 0 deletions patterns/dynamic-programming/second-approach.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// brute force recursive
let knapsack = function (profits, weights, capacity) {
function recursiveHelper(profits, weights, capacity, idx) {
if (capacity <= 0 || idx >= profits.length) return 0;

let prf1 = 0;
if (weights[idx] <= capacity) {
prf1 =
profits[idx] +
recursiveHelper(profits, weights, capacity - weights[idx], idx + 1);
}

const prf2 = recursiveHelper(profits, weights, capacity, idx + 1);

return Math.max(prf1, prf2);
}

return recursiveHelper(profits, weights, capacity, 0);
};

var profits = [1, 6, 10, 16];
var weights = [1, 2, 3, 5];

console.log(knapsack(profits, weights, 7));
console.log(knapsack(profits, weights, 6));