Practice Real Company Assessment Patterns • Latest 2025–2026 Mock Tests

Programming Exercises

Write a function to solve the knapsack problem, finding the maximum value obtainable within a weight limit.

Hard

Problem 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 = 5

Sample 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));
Log in or sign up to run or submit your code.Log inSign up
Input
items = [ { weight: 2, value: 3 }, { weight: 3, value: 4 }, { weight: 4, value: 5 } ]
capacity = 5
Expected Output
7