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)?
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 capacit...read more
(i) = the highest total value that can be achieved from a knapsack with capacity i. V (8) = max[r1 + V (5), r2 + V (0), r3 + V (3)] = max[4 + 5, 6+0, 5 + 4] = 9. Thus, the optimal value is 9, which is...read more
Top TCS System Engineer interview questions & answers
Popular interview questions of System Engineer
Top HR questions asked in TCS System Engineer
Reviews
Interviews
Salaries
Users/Month