0 - 1 Knapsack
A thief is robbing a store and can carry a maximum weight of ‘W’ into his knapsack. There are 'N' items available in the store and the weight and value of each item is known to the thief. Considering the constraints of the maximum weight that a knapsack can carry, you have to find the maximum profit that a thief can generate by stealing items.
Note: The thief is not allowed to break the items.
For example, N = 4, W = 10 and the weights and values of items are weights = [6, 1, 5, 3] and values = [3, 6, 1, 4]. Then the best way to fill the knapsack is to choose items with weight 6, 1 and 3. The total value of knapsack = 3 + 6 + 4 = 13.
Input Format:
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, respectively.
The second line contains 'N' space-separated integers, that denote the values of the weight of items.
The third line contains 'N' space-separated integers, that denote the values associated with the items.
Output Format :
The first and only line of output contains the maximum profit that a thief can generate, as described in the task.
The output of every test case is printed in a separate line.
Constraints:
1 <= T <= 10
1 <= N <= 10^2
1 <= W <= 10^2
1<= weights <= 50
1 <= values <= 10^2
where 'T' is the number of test cases, ‘N’ is the number of items, "weights" is the weight of each item, "values" is the value of each item and ‘W’ is the maximum weight the thief can carry.
CodingNinjas
author
2y
Recursion
This problem can be solved by solving its subproblems and then combining the solutions of the solved subproblems to solve the original problem. We will do this using recursion.
We will conside...read more
CodingNinjas
author
2y
Memoization
We are solving this problem by solving its subproblems and then combining the solutions of those subproblems. If we analyze carefully, we will see that we are solving the same subproblems m...read more
CodingNinjas
author
2y
Dynamic Programming
Initially, we were breaking the large problem into small problems but now, let us look at it in a different way. Can you solve the small problem first and then reach the final answe...read more
CodingNinjas
author
2y
Space Optimized DP
Basically, in the previous approach, you can observe that:
- If you include the item i with total knapsack weight being j:
- You look for the previous row of the 2D matrix with the require...read more
Add answer anonymously...
Top Samsung Software Developer Intern interview questions & answers
Popular interview questions of Software Developer Intern
Stay ahead in your career. Get AmbitionBox app
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
Get AmbitionBox app