You are given an array of integers "ARR" of length 'N' and an integer 'K'. Your task is to find whether or not you can divide the array "ARR" into 'K' subsets with equal sum.
A subset of an array "ARR" is another array whose every element is present in array "ARR".
For example:If ARR = {1, 2, 3, 4}, then array {3,4} is a subset of "ARR" because both 3 and 4 are also elements of "ARR".
For example:
Consider array ARR = {3, 5, 2, 4, 4} and K = 2, i.e. you have to divide "ARR" into 2 subsets with equal sum. The division will be {4, 5} and {2, 3, 4} with sum 9.
Note:
Every element of the array must occupy only one subset.
Input Format:
The first line of input contains an integer 'T' representing the number of the test case. Then the test case follows.
The first line of each test case contains two space-separated integers ‘N’ representing the size of the array and ‘K’.
The second line contains N space-separated integers that represent elements of the array ARR.
Output Format
For each test case, return true if it is possible to divide "ARR" into 'K' subsets of equal sum, false otherwise.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 100
1 <= N <=1000
1 <= K <= 20
1 <= ARR[i] <= 1000
Time limit: 1 second
3
5 2
3 5 2 4 4
9 6
1 9 6 8 6 9 9 9 9
7 4
4 4 4 1 1 1 1
TRUE
FALSE
TRUE
For first case,
Array can be divided into 2 subsets as {2, 3, 4} and {4, 5} with sum 9.
For the second case,
Array can not be divided into 6 subsets with equal sum.
For the third case,
Array can be divided into 4 subsets as {4}, {4}, {4} and {1, 1, 1, 1} with sum 4.
5
10 5
1 2 3 4 5 6 7 8 9 10
7 7
7 7 7 7 7 7 7
7 3
1 2 3 4 5 6 7
5 2
3 5 7 11 13
3 5
1 2 3
TRUE
TRUE
FALSE
FALSE
FALSE
Try to find what is the maximum sum value you can use to make a subset, then make each subset one by one.
Consider function “SPLITARRAY” that accepts array “ARR” and ‘K’ and do
Now, the utility function “SPLITARRAYUTIL” which we used earlier basically picks all the elements of “ARR" one by one and places them in available subsets until the max sum limit of the array is reached. It accepts integer array "ARR", the value 'K', size of array ‘N’, integer array “SUMOFSUBSETS”, boolean array “ISCONSIDERED”, the max limit of sum for a subset "SUBSET", the current index for subset “CURRINDEX” and upper index limit “MAXLIMIT” as parameters and does:
O(K ^ (N - K) * K!) where ‘N’ is the length of the array and ‘K’ is the number of subsets.
We try each combination of divisions that costs K ^ (N - K) operations, and since the number of ways to order the subsets is K!, the overall complexity is O(K ^ (N - K) * K!).
O(K ^ (N - K) * K!) where ‘N’ is the length of the array and ‘K’ is the number of subsets.
We try each combination of divisions that costs K ^ (N - K) recursive calls, and since the number of ways to order the subsets is K!, the overall recursive depth is O(K ^ (N - K) * K!).