Given an even number N, the task is to split all N powers of 2 into two sets such that the difference of their sum is minimum.
Input: n = 4
Here n = 4 which means we have 21, 22, 23, 24. The most optimal way to divide it into two groups with equal element is 24 + 21 in one group and 22 + 23 in another group giving a minimum possible difference of 6.
Input: n = 8
Here n = 8 which means we have 21, 22, 23, 24, 25, 26, 27, 28. The most optimal way to divide it into two groups with equal element is 28 + 21 + 22 + 23 in one group and 24 + 25 + 26 + 27 in another group giving a minimum possible difference of 30.
Approach: To solve the problem mentioned above we have to follow the steps given below:
- In the first group add the largest element that is 2N.
- After adding the first number in one group, add N/2 – 1 more elements to this group, where the elements has to start from the least power of two or from the beginning of the sequence.
For example: if N = 4 then add 24 to the first group and add N/2 – 1, i.e. 1 more element to this group which is the least which means is 21.
- The remaining element of the sequence forms the elements of the second group.
- Calculate the sum for both the groups and then find the absolute difference between the groups which will eventually be the minimum.
Below is the implementation of the above approach:
Time complexity: O(N)
Auxiliary Space: O(1)