0-1 Knapsack Problem

A thief is planning to rob a store and has a knapsack that can carry a maximal weight of W. There are N items available, where each item i has a weight wi and a value vi. Determine the maximum total value of items the thief can carry without exceeding the weight limit of the knapsack.

Input:

The first line contains a single integer T, representing the number of test cases. 
For each test case, the input consists of:
  • An integer N, denoting the number of items.
  • N space-separated integers representing the weights of the items.
  • N space-separated integers representing the values of the items.
  • An integer W, denoting the maximum capacity of the knapsack.

Output:

For each test case, output a single integer representing the maximum value that can be attained without exceeding the knapsack's weight capacity. Each result should be printed on a new line.

Example:

Input:
1
4
2 3 4 5
3 4 5 6
5
Output:
7
Explanation:

In the given test case, the thief can carry items with weight 2 and 3 for a total value of 3 + 4 = 7, which is the maximum possible value without exceeding the capacity W=5.

Constraints:

  • 1 <= T <= 10
  • 1 <= N <= 10^2
  • 1 <= wi <= 50
  • 1 <= vi <= 10^2
  • 1 <= W <= 10^3
  • Time Limit: 1 second
Note:

Can this problem be solved with a space complexity of no more than O(W)?

AnswerBot
4mo

Yes, the 0-1 Knapsack Problem can be solved using dynamic programming with a space complexity of O(W).

  • Use dynamic programming to create a 2D array to store the maximum value that can be attained at ea...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Intern Interview Questions Asked at Delhivery

Q. Trapping Rain Water Problem Statement You are given a long type array/list ARR o...read more
Q. Maximum Value of Modulus Expression Problem You are provided with two arrays ARR...read more
Q. Reverse Linked List Problem Statement Given a Singly Linked List of integers, yo...read more
Software Developer Intern 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