Given a positive integer n such that n > 2. Divide numbers from 1 to n in two groups such that absolute difference of sum of each group is minimum. Print any two groups with their size in first line and in next line print elements of that group.
Input : 5 Output : 2 5 2 3 4 3 1 Here sum of group 1 is 7 and sum of group 2 is 8. Their absolute difference is 1 which is minimum. We can have multiple correct answers. (1, 2, 5) and (3, 4) is another such group. Input : 6 Output : 2 6 4 4 5 3 2 1
We can always divide sum of n integers in two groups such that their absolute difference of their sum is 0 or 1. So sum of group at most differ by 1. We define sum of group1 as half of n elements sum.
Now run a loop from n to 1 and insert i into group1 if inserting an element doesn’t exceed group1 sum otherwise insert that i into group2.
2 5 2 3 4 3 1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Improved By : Mithun Kumar
- Minimize Cash Flow among a given set of friends who have borrowed money from each other
- Check whether given three numbers are adjacent primes
- Print a closest string that does not contain adjacent duplicates
- Coin Change | DP-7
- Minimum cost to make array size 1 by removing larger of pairs
- Value in a given range with maximum XOR
- Kruskal’s Algorithm (Simple Implementation for Adjacency Matrix)
- Prim’s Algorithm (Simple Implementation for Adjacency Matrix Representation)
- Number of chocolates left after k iterations
- Subarray whose absolute sum is closest to K