Write a function to solve the knapsack problem, finding the maximum value obtainable within a weight limit.
HardProblem Statement
Write a function to solve the knapsack problem, finding the maximum value obtainable within a weight limit.
Sample Input
items = [ { weight: 2, value: 3 }, { weight: 3, value: 4 }, { weight: 4, value: 5 } ]
capacity = 5Sample Output
7
Limits
Time: 2s · Memory: 256 MB
Code Editor
00:00
// Solve the knapsack problem
function knapsack(items, capacity) {
// Initialize a 2D array for dynamic programming
// Update the array based on weight and value of each item
}
console.log(knapsack([ { weight: 2, value: 3 }, { weight: 3, value: 4 }, { weight: 4, value: 5 } ], 5));
Input
items = [ { weight: 2, value: 3 }, { weight: 3, value: 4 }, { weight: 4, value: 5 } ]
capacity = 5Expected Output
7