Maximize profit by picking elements of different types with total weight K
Given an array item representing type, weight, and profit of N items, the task is to maximize the profit by picking different types of elements (i.e., no two elements are of the same type) such that the total weight is at most pick atmost K.
Input: item = [[1, 3, 13], [5, 1, 10], [2, 2, 1], [1, 4, 9], [4, 5, 11], [1, 5, 9] ], K = 6
Explanation: The maximum value obtained is 24.
You can take items of type1 with a profit of 13 and type5 with a profit of 10 and type2 with a profit of 1.
Hence the value = 13 + 10 + 1 = 24
Input: item = [[1, 3, 13], [5, 1, 10], [2, 2, 1], [1, 4, 9], [4, 5, 11], [1, 5, 9] ], K = 9
Explanation: The maximum value obtained is 34.
You can take items of type1 with a profit of 13 and of type5 with a profit of 10 and type4 with a profit of 11. H
ence the value = 13 + 10 + 11 = 34
Approach: The problem can be solved using recursion based on the following idea:
For each element of the item, we are having two choices whether to take that particular item or not.
- Case 1 – Pick Case: When the weight of the item present at item[index] is less than or equal to K as well as the item of that type has not been brought so far, the profit of that item will get add up in our total value and the total weight K will get reduced by the weight of the current item and type of that item will get add up to the set saying this type item had been taken.
- Case 2 – Not Pick Case: When the item present at item[index] does not get included in the final result, no profit i.e. 0 will get added up in our total value.
You can include items if and only if the current item weight is less than or equal to the total weight available and an item of that type has not been brought so far.
Follow the steps mentioned below to implement the idea:
- Create a recursive function.
- For each call, there are two choices for the item as mentioned above.
- Calculate the value of all possible cases as mentioned above.
- The maximum among them is the required answer.
Below is the implementation of the above approach:
Maximum value obtained: 24
Time Complexity: O(2N)
Auxiliary Space: O(N)
- Introduction to Dynamic Programming – Data Structures and Algorithms tutorials
- 0 – 1 Knapsack Problem