0/1 Knapsack Problem Statement

A thief is planning to rob a store and can carry a maximum weight of 'W' in his knapsack. The store contains 'N' items where the ith item has a weight of 'wi' and a value of 'vi'. Given the maximum weight capacity of the knapsack, determine the maximum total value of items that the thief can steal.

Input:

The first line contains an integer 'T' representing the number of test cases.
Each test case includes:
1. An integer 'N' denoting the number of items.
2. A line with 'N' space-separated integers representing the weights of the items.
3. A line with 'N' space-separated integers representing the values of the items.
4. An integer 'W' denoting the maximum weight capacity of the knapsack.

Output:

For each test case, output a single integer denoting the maximum value that can be stolen. Each result should be printed on a new line.

Example:

Input:
2
3
10 20 30
60 100 120
50
3
1 2 3
10 20 30
5
Output:
220
50

Constraints:

  • 1 <= T <= 10
  • 1 <= N <= 10^2
  • 1 <= wi <= 50
  • 1 <= vi <= 10^2
  • 1 <= W <= 10^3

Follow-Up:

Can the problem be solved using a space complexity of not more than O(W)?
AnswerBot
4d

Yes, the 0/1 Knapsack problem can be solved using dynamic programming with a space complexity of not more than O(W).

  • Use a 1D array to store the maximum value that can be stolen for each weight from 0 ...read more

Help your peers!
Add answer anonymously...
Ansys Software Private Limited Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

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

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter