


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.
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
In the recursive approach, some problems are solved again and again.
Let us see a recursion tree for ‘W’ =7, ‘N’ = 4 , 'PROFIT' =[1,6,10,16], ‘WEIGHT’ = [1,2,3,5].
It is clear from the recursion tree that the problem for ‘N’ = 1 and ‘W’ = 5 is solved for two times.
The recursive approach can be optimized by maintaining an extra 2-d array ‘RES’ that stores the result of the recursive calls. For every sub-problem, we first check the 'RES' array. If the value is already computed we simply return it otherwise we calculate it using recursion and put it in the “res” array.
Algorithm
We will solve the problem in a bottom-up manner. We will compute the result for all values of knapsack capacity from 0 to W. We will maintain a 1-D array ‘DP’ of size ‘W+1’ with all its initial values as 0. ‘DP[ i ]’ stores the maximum profit that can be obtained by using all items and knapsack capacity ‘ i ‘.
For every value of ‘ i ‘, we will check for all items. If the weight of any item at index ‘ j ’ say ‘WEIGHT[ j ]’ is smaller than current knapsack capacity i.e ‘ i ’, that means we can include that item, and ‘DP[ i ]’ will be max ( DP[ i ], PROFIT [ j ] + profit when knapsack capacity = i - WEIGHT[ j ].)
DP [ W ] will store the required answer.
Algorithm