From 26540dd6caad2cb6bca8c67c4e1ba35938cecd68 Mon Sep 17 00:00:00 2001 From: techcursed <31003460+techcursed@users.noreply.github.com> Date: Wed, 4 Oct 2023 15:03:20 +0530 Subject: [PATCH] feat: add UnboundedKnapsack algorithm --- DIRECTORY.md | 1 + Dynamic-Programming/UnboundedKnapsack.js | 36 ++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 Dynamic-Programming/UnboundedKnapsack.js diff --git a/DIRECTORY.md b/DIRECTORY.md index 31969e4cd1..fa94fe5da9 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -118,6 +118,7 @@ * [RodCutting](Dynamic-Programming/RodCutting.js) * [Shuf](Dynamic-Programming/Shuf.js) * [SieveOfEratosthenes](Dynamic-Programming/SieveOfEratosthenes.js) + * [UnboundedKnapsack](Dynamic-Programming/UnboundedKnapsack.js) * **Sliding-Window** * [HouseRobber](Dynamic-Programming/Sliding-Window/HouseRobber.js) * [LongestSubstringWithoutRepeatingCharacters](Dynamic-Programming/Sliding-Window/LongestSubstringWithoutRepeatingCharacters.js) diff --git a/Dynamic-Programming/UnboundedKnapsack.js b/Dynamic-Programming/UnboundedKnapsack.js new file mode 100644 index 0000000000..eb0ee09fb6 --- /dev/null +++ b/Dynamic-Programming/UnboundedKnapsack.js @@ -0,0 +1,36 @@ +/** + * @function unboundedKnapsack + * @description Solve the Unbounded Knapsack problem using Dynamic Programming. + * @param {number[]} weights - An array of item weights. + * @param {number[]} values - An array of item values. + * @param {number} capacity - The maximum capacity of the knapsack. + * @return {number} The maximum value that can be obtained. + * @see [UnboundedKnapsack](https://en.wikipedia.org/wiki/Knapsack_problem#Unbounded_knapsack_problem) + */ + +function unboundedKnapsack(weights, values, capacity) { + const n = weights.length; + + // Create a DP array to store the maximum value for each possible knapsack capacity. + const dp = new Array(capacity + 1).fill(0); + + // Loop through each possible knapsack capacity from 0 to the maximum capacity. + for (let w = 0; w <= capacity; w++) { + // Loop through each item in the given items. + for (let i = 0; i < n; i++) { + // Check if the weight of the current item is less than or equal to the current knapsack capacity. + if (weights[i] <= w) { + // Update the DP array with the maximum value between not taking the current item + // and taking the current item and adding its value. + dp[w] = Math.max(dp[w], dp[w - weights[i]] + values[i]); + } + } + } + + // The final element of the DP array stores the maximum value that can be obtained with + // the given knapsack capacity. + return dp[capacity]; + } + + export { unboundedKnapsack }; + \ No newline at end of file

AltStyle によって変換されたページ (->オリジナル) /