Skip to content

feat: add UnboundedKnapsack algorithm #1428

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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 DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
36 changes: 36 additions & 0 deletions Dynamic-Programming/UnboundedKnapsack.js
Original file line number Diff line number Diff line change
@@ -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 };