0/1 Knapsack Problem Statement

A thief is planning to rob a store and can carry a maximum weight 'W' in their knapsack. The store contains 'N' items, each with a known weight and value. Given these constraints, determine the maximum profit that the thief can generate by selecting items to steal, without breaking any item.

Note: Items cannot be broken; they must be taken whole.

Example:

Input:
N = 4, W = 10, weights = [6, 1, 5, 3], values = [3, 6, 1, 4]
Output:
13
Explanation:

The best way to fill the knapsack is by selecting items with weights 6, 1 and 3, making the total value of the knapsack to be 3 + 6 + 4 = 13.

Constraints:

  • 1 <= T <= 10
  • 1 <= N <= 10^3
  • 1 <= W <= 10^3
  • 1 <= weights[i] <= 10^3
  • 1 <= values[i] <= 10^3

Input:

The first line contains a single integer 'T', representing the number of test cases.
The 'T' test cases are as follows:
The first line contains two integers 'N' and 'W', denoting the number of items and the maximum weight the thief can carry.
The second line contains 'N' space-separated integers representing the weights of the items.
The third line contains 'N' space-separated integers representing the values of the items.

Output:

The output for each test case is a single line containing the maximum profit the thief can generate.
AnswerBot
4mo

The 0/1 Knapsack Problem involves maximizing profit by selecting items with known weights and values to fit within a knapsack of limited capacity.

  • Create a 2D array to store the maximum profit that can...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Nagarro

Q. Design and implement a data structure for Least Recently Used (LRU) cache. It sh...read more
Q. Given the root of a binary search tree, and an integer k, return the kth smalles...read more
Q. What is abstraction in Java?
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