Skip to content

Refactor 0-1 Knapsack Implementation #236

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

Merged
merged 3 commits into from
Apr 8, 2024
Merged
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
70 changes: 34 additions & 36 deletions dynamic_programming/knapsack.ts
Original file line number Diff line number Diff line change
@@ -1,56 +1,54 @@
/**
* @function knapsack
* @description Given weights and values of n (numberOfItems) items, put these items in a knapsack of capacity to get the maximum total value in the knapsack. In other words, given two integer arrays values[0..n-1] and weights[0..n-1] which represent values and weights associated with n items respectively. Also given an integer capacity which represents knapsack capacity, find out the maximum value subset of values[] such that sum of the weights of this subset is smaller than or equal to capacity. You cannot break an item, either pick the complete item or don’t pick it (0-1 property).
* @Complexity_Analysis
* Space complexity - O(1)
* Time complexity (independent of input) : O(numberOfItems * capacity)
*
* @return maximum value subset of values[] such that sum of the weights of this subset is smaller than or equal to capacity.
* @see [Knapsack](https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/)
* @example knapsack(3, 8, [3, 4, 5], [30, 50, 60]) = 90
* Solves the 0-1 Knapsack Problem.
* @param capacity Knapsack capacity
* @param weights Array of item weights
* @param values Array of item values
* @returns Maximum value subset such that sum of the weights of this subset is smaller than or equal to capacity
* @throws If weights and values arrays have different lengths
* @see [Knapsack](https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/)
* @example knapsack(3, [3, 4, 5], [30, 50, 60]) // Output: 90
*/

export const knapsack = (
capacity: number,
weights: number[],
values: number[]
) => {
if (weights.length != values.length) {
): number => {
if (weights.length !== values.length) {
throw new Error(
'weights and values arrays should have same number of elements'
'Weights and values arrays should have the same number of elements'
)
}

const numberOfItems = weights.length
const numberOfItems: number = weights.length

// Declaring a data structure to store calculated states/values
// Initializing a 2D array to store calculated states/values
const dp: number[][] = new Array(numberOfItems + 1)

for (let i = 0; i < dp.length; i++) {
// Placing an array at each index of dp to make it a 2d matrix
dp[i] = new Array(capacity + 1)
}
.fill(0)
.map(() => new Array(capacity + 1).fill(0))

// Loop traversing each state of dp
for (let i = 0; i < numberOfItems; i++) {
for (let j = 0; j <= capacity; j++) {
if (i == 0) {
if (j >= weights[i]) {
// grab the first item if it's weight is less than remaining weight (j)
dp[i][j] = values[i]
} else {
// if weight[i] is more than remaining weight (j) leave it
dp[i][j] = 0
}
} else if (j < weights[i]) {
// if weight of current item (weights[i]) is more than remaining weight (j), leave the current item and just carry on previous items
dp[i][j] = dp[i - 1][j]
for (let itemIndex = 1; itemIndex <= numberOfItems; itemIndex++) {
const weight = weights[itemIndex - 1]
const value = values[itemIndex - 1]
for (
let currentCapacity = 1;
currentCapacity <= capacity;
currentCapacity++
) {
if (weight <= currentCapacity) {
// Select the maximum value of including the current item or excluding it
dp[itemIndex][currentCapacity] = Math.max(
value + dp[itemIndex - 1][currentCapacity - weight],
dp[itemIndex - 1][currentCapacity]
)
} else {
// select the maximum of (if current weight is collected thus adding it's value) and (if current weight is not collected thus not adding it's value)
dp[i][j] = Math.max(dp[i - 1][j - weights[i]] + values[i], dp[i - 1][j])
// If the current item's weight exceeds the current capacity, exclude it
dp[itemIndex][currentCapacity] = dp[itemIndex - 1][currentCapacity]
}
}
}

// Return the final maximized value at last position of dp matrix
return dp[numberOfItems - 1][capacity]
// Return the final maximized value at the last position of the dp matrix
return dp[numberOfItems][capacity]
}
Loading