From 855d7c37a2d001d172befefd2ec959671452f246 Mon Sep 17 00:00:00 2001 From: Chinedu Abalogu Date: Sun, 9 Oct 2022 21:26:41 +0100 Subject: [PATCH] brute force recursive approach --- .../0-1knapsack/first-approach.js | 1 + .../dynamic-programming/second-approach.js | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 patterns/dynamic-programming/second-approach.js diff --git a/patterns/dynamic-programming/0-1knapsack/first-approach.js b/patterns/dynamic-programming/0-1knapsack/first-approach.js index cb7f054..68de532 100644 --- a/patterns/dynamic-programming/0-1knapsack/first-approach.js +++ b/patterns/dynamic-programming/0-1knapsack/first-approach.js @@ -1,3 +1,4 @@ +// wrong const knapsack = (profits, weights, capacity) => { let result = [0, 0]; let mp = 0; diff --git a/patterns/dynamic-programming/second-approach.js b/patterns/dynamic-programming/second-approach.js new file mode 100644 index 0000000..0f0fdc6 --- /dev/null +++ b/patterns/dynamic-programming/second-approach.js @@ -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));