![]() |
VOOZH | about |
Given two integers N, K and two integer arrays weights[] and profits[] each of size N where weights[i] is the weight associated with the ith item and profit[i] is the profit associated with the ith item. Maximize the profit by selecting a subset of items such that the bitwise OR of their weights is less than or equal to the given threshold K.
Examples:
Input: N = 5, K = 15, weights[] = {9, 5, 12, 7, 8}, profits[] = {20, 15, 30, 12, 18}
Output: 95
Explanation: Our task is to select a subset of weights such that their bitwise OR is less than or equal to 15. The bitwise OR of 9, 5, 12, 7 and 8 is 15, satisfying the OR condition. Thus, the maximum possible sum of profits is 95, as weights 9, 5, 12, 7 and 8 are selected.Input: N = 4, K = 6, weights[] = {3, 4, 2, 1}, profits[] = {10, 12, 8, 6}
Output: 24
Explanation: Our task is to select a subset of weights such that their bitwise OR is less than or equal to 6. The bitwise OR of 3, 2, and 1 is 3, satisfying the OR condition. Thus, the maximum possible sum of profits is 47, as weights 3, 2, and 1 are selected.
Approach: This can be solved using the following approach:
The approach is to use Recursion to evaluate all possible combinations of items to find the subset that maximizes the sum of profits while ensuring that the bitwise OR operation of the selected items does not exceed the specified threshold K
Steps to solve the problem:
Below is the implementation of the above approach:
95
Time Complexity: O(2^N), where N is the size of weights[] and profits[] array
Auxiliary Space: O(N)