You are given an array ‘arr’ of size ‘N’ and an integer ‘K’. Your task is to find the maximum subset-sum of the array that is not greater than ‘K’.
For Example:Your are given ‘arr’ = [1, 3, 5, 9], and ‘K’ = 16, we can take the subset of elements [9, 5 ,1] which sums up to 15. Hence the answer is 15.
The first line of input contains a single integer ‘T’ representing the number of test cases.
The first line of each test case contains two space-separated integers, ‘N’ and ‘K’, denoting the number of elements and the given integer.
The second line of each test case contains ‘N’ space-separated integers representing the elements of the array.
Output Format:
For each test case, print a single integer representing the maximum subset-sum not greater than ‘K.’
Print a separate line for each test case.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 40
0 <= K <= 10^9
0 <= arr[i] <= 10^9
Time Limit: 1 sec
2
4 16
1 3 5 9
6 10
3 34 4 12 5 2
15
10
For the first test case, You are given ‘arr’ = [1, 3, 5, 9], and ‘K’ = 16. We can take the subset of elements [9, 5, 1] which sums up to 15. Hence the answer is 15.
For the second test case, you are given ‘arr’ = [3, 34, 4, 12, 5, 2], and ‘K’ = 10. We can take the subset of elements [3, 2, 5] which sums up to 10. Hence the answer is 10.
2
5 1
10 2 18 4 5
1 10
5
0
5
Try to find the sum of each subset.
In this approach, we will iterate over all the possible subsets of the given array, and then we will find the maximum sum subset whose sum is not greater than K.
The total number of subsets of an array is 2^N or 1 << N in the bitshift operator.
Algorithm:
O(N*(2^N)), Where N is the number of elements in the array.
We iterate through over all the subsets of the array that takes O(2^N) time. For each subset, we are also calculating the sum of the subset. Hence the overall time complexity is O(N*2^(N)).
O(1).
No extra space is used in this algorithm. Hence the overall space complexity is O(1).