You are given ‘n’ items with certain ‘profit’ and ‘weight’ and a knapsack with weight capacity ‘w’.
You need to fill the knapsack with the items in such a way that you get the maximum profit. You are allowed to take one item multiple times.
Input:
'n' = 3, 'w' = 10,
'profit' = [5, 11, 13]
'weight' = [2, 4, 6]
Output: 27
Explanation:
We can fill the knapsack as:
1 item of weight 6 and 1 item of weight 4.
1 item of weight 6 and 2 items of weight 2.
2 items of weight 4 and 1 item of weight 2.
5 items of weight 2.
The maximum profit will be from case 3 = 11 + 11 + 5 = 27. Therefore maximum profit = 27.
The first line of input contains two integers ‘n’ and ‘w’ - number of items and weight capacity of the knapsack.
The second line of each test case contains 'n' integers - elements of 'profit' array.
The third line of each test case contains 'n' integers - elements of 'weight' array.
Return an integer denoting the maximum profit that can be obtained by filling the knapsack.
You do not need to print anything; it has already been taken care of. Just implement the given function.
3 15
7 2 4
5 10 20
21
21
The given knapsack capacity is 15. We can fill the knapsack as [1, 1, 1] giving us profit 21 and as [1,2] giving us profit 9. Thus maximum profit will be 21.
2 3
6 12
4 17
0
0
We can clearly see that no item has weight less than knapsack capacity. Therefore we can not fill knapsack with any item.
Try to solve this in O(n*w).
1 <= n <= 10^3
1 <= w <= 10^3
1 <= profit[i] , weight[i] <= 10^8
Time Limit: 1 sec
Try to find all possible sequences of items using recursion.
A simple idea is to consider all possible sequence of items that have a total weight not more than ‘W’ and find the subset which gives maximum profit.
Algorithm
O(2^N), where ‘N’ is the total number of items.
Recursion will lead to exponential time complexity. Therefore time complexity is of order 2^N.
O(2^N), where ‘N’ is the total number of items.
Recursion will lead to exponential calls of the functions which will be store in stack. Therefore space complexity is of order 2^N.