![]() |
VOOZH | about |
Given a positive integer n, such that n > 2. Your task is to divide the numbers from 1 to n in two groups, such that the absolute difference between the sum of the elements of the these two groups is minimum possible.
Examples:
Input: n = 5
Output: [ [ 2, 5 ], [ 1, 3, 4 ] ]
Explanation: The sum of first and second group are 7 and 8 respectively, and the difference is 8 - 7 = 1, which is the minimum possible. [ [ 1, 2, 5 ], [ 3, 4 ] ] is also the possible solution.Input: n = 7
Output: [ [ 1, 6, 7 ], [ 2, 3, 4, 5 ] ]
Explanation: The sum of first and second group are 14 and 14 respectively, and the difference is 14 - 14 = 0, which is the minimum possible.
This problem can be reduced to the subset sum problem. We mainly need to find a subset of [1, 2, ... n] whose sum is closest to half of n*(n+1)/2. The time complexity of this solution would be O(n^3).
Subset 1: 1 4 Subset 2: 2 3
We traverse numbers from n to 1. And we try adding every number to the first subset. If adding the number does not make the sum more than half, we add the number to first subset, else to the second.
We create two auxiliary arrays to store the elements of two groups, and initiate two counters to store the sum of elements of both the groups. Now start iterating from 1 to n, and insert the element in the first group if it does not exceed the first group's sum more than the calculated half sum, else insert the element in second group.
7 6 1 5 4 3 2
Time Complexity: O(n), as we are iterating from n to 1 only once.
Space Complexity: O(n), to store the elements from 1 to n in two groups.