0-1 Knapsack Problem Statement

A thief plans to rob a store and can carry a maximum weight 'W' in his knapsack. There are 'N' items, with the i-th item weighing wi and having a value vi. Determine the maximum value the thief can obtain while respecting the knapsack's weight limit.

Input:

 The input begins with an integer 'T', representing the number of test cases. 
 For each test case, the format is as follows: 
 An integer 'N', the number of items. 
 N space-separated integers indicating the weights of the items. 
 N space-separated integers indicating the values of the items. 
 An integer 'W', the maximum weight the knapsack can carry. 

Output:

 For each test case, output a single line containing the maximum value achievable with the given constraints. 

Example:

Input:
 2 
3
1 2 3
10 15 40
6
2
1 2
10 20
2
Output:
 55 
20

The first test case shows the optimal value from weights [1, 2, 3] with values [10, 15, 40] when weight is restricted to 6, the maximum value is 55. The second case shows that only one item with value 20 can be taken.

Constraints:

  • 1 ≤ T ≤ 10
  • 1 ≤ N ≤ 102
  • 1 ≤ wi ≤ 50
  • 1 ≤ vi ≤ 102
  • 1 ≤ W ≤ 103

Time Limit: 1 second

Note:

You are not required to print anything; the function will return the answer.

AnswerBot
4mo

The 0-1 Knapsack Problem involves maximizing the value of items in a knapsack while respecting weight constraints.

  • Iterate through all possible combinations of items to find the optimal solution.

  • Use dy...read more

Help your peers!
Select
Add answer anonymously...

Popular interview questions of Software Developer

A Software Developer was asked Q1. Reverse Linked List Problem Statement Given a Singly Linked List of integers, yo...read more
A Software Developer was asked Q2. Longest Palindromic Substring Problem Statement You are provided with a string S...read more
A Software Developer was asked Q3. 0-1 Knapsack Problem Statement A thief plans to rob a store and can carry a maxi...read more
Algo8 AI Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits