Given a number n, divide first n natural numbers (1, 2, …n) into two subsets such that difference between sums of two subsets is minimum.
Input : n = 4 Output : First subset sum = 5, Second subset sum = 5. Difference = 0 Explanation: Subset 1: 1 4 Subset 2: 2 3 Input : n = 6 Output: First subset sum = 10, Second subset sum = 11. Difference = 1 Explanation : Subset 1: 1 3 6 Subset 2: 2 4 5
The approach is based on the fact that any four consecutive numbers can be divided into two groups by putting middle two elements in one group and corner elements in other group. So, if n is a multiple of 4 then their difference will be 0, hence the summation of one set will be half of the summation of N elements which can be calculated by using sum = n*(n+1)/2
There are three other cases to consider in which we cannot divide into groups of 4, which will leave a remainder of 1, 2 and 3:
a) If it leaves a remainder of 1, then all other n-1 elements are clubbed into group of 4 hence their sum will be int(sum/2) and the other half sum will be int(sum/2+1) and their difference will always be 1.
b) Above mentioned steps will be followed in case of n%4 == 2 also. Here we form groups of size 4 for elements from 3 onward. Remaining elements would be 1 and 2. 1 goes in one group and 2 goes in other group.
c) When n%4 == 3, then club n-3 elements into groups of 4. The left out elements will be 1, 2 and 3, in which 1 and 2 will go to one set and 3 to the other set which eventually makes the difference to be 0 and summation of each set to be sum/2.
Below is the implementation of the above approach:
First subset sum = 10 Second subset sum = 11 Difference = 1
- Minimize the maximum difference between the heights
- Delete Edge to minimize subtree sum difference
- Minimize the difference between the maximum and minimum values of the modified array
- Maximum sum of absolute difference of an array
- Triplets in array with absolute difference less than k
- Sort an array according to absolute difference with given value
- k-th smallest absolute difference of two elements in an array
- Closest Palindrome Number (absolute difference Is min)
- Maximum absolute difference between sum of two contiguous sub-arrays
- Minimum absolute difference of XOR values of two subarrays
- Minimum sum of absolute difference of pairs of two arrays
- Maximum absolute difference of value and index sums
- Sum of minimum absolute difference of each array element
- Python | Sort an array according to absolute difference
- Pair with minimum absolute difference after solving each query
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : vt_m