Given a positive integer ‘N’. Divide numbers from 1 to ‘N’ in two groups such that the absolute difference of sum of each group is minimum and print the absolute difference.
Example :
If ‘N’ : 3
Then the two groups can be : {3} and {2, 1}
The absolute difference of sum between above two groups is : 0
The first line of input contains an integer ‘T’ representing the number of test cases.
Then the test cases follow :
The only line of each test case contains a single integer ‘N’.
Output Format :
For each test case, print the minimum absolute difference of sum of each group.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10^2
2 <= N <= 10^4
Time Limit : 1 sec
2
4
2
0
1
For first test case,
First group can be {1, 4}, sum of first group is : 4 + 1 = 5
Second group can be {2, 3}, sum of second group is : 3 + 2 = 5
Minimum absolute difference : |5 - 5| = 0
For second test case,
First group can be {1}, sum of first group is : 1
Second group can be {2}, sum of second group is: 2
Minimum absolute difference : |1 - 2| = 1
1
5
1
First group can be {2, 5}, sum of first group is : 5 + 2 = 7
Second group can be {1, 3, 4}, sum of second group is : 4 + 3 + 1 = 8
Minimum absolute difference : |7 - 8| = 1
Try to find all the possible sums.
The naive approach for this is to generate all the possible sums by including i’th number in a group or not, and then find the optimal solution.
Here is the algorithm :
HELPER(‘SUM’, ‘i’, ‘group1Sum’)
O(2^N), where ‘N’ denotes the given positive integer.
Each number has two choices, whether to include it in a ‘GROUP1’ or not. There are total ‘N’ numbers present with us, so the total possible combinations will be 2*2*2… (‘N’ times). Therefore, the overall time complexity will be O(2^N).
O(N).
This space is used to store the recursion stack. Our algorithm works in a depth - first way, so we cannot have more than ‘N’ recursive calls on the stack as the total numbers present can be at max ‘N’. Therefore, the overall space complexity will be O(N).