1
$\begingroup$

Let's say for some $n$ we have the sequence $1, 2, 3, \dots , n$, what we want with this sequence is to divide it in two sets such that each element of the sequence will be in only one set, and the difference in sums of the two sets will be minimum possible.

Example

Let $n = 4$, and $A$ and $B$ are our sets, we can divide the numbers in this set such that the difference in sum between them will be $0$, $A = \{1, 4\}$ and $B = \{2,3\}$

My thinking

I noticed we can divide like this $1$ and $n$ in set $A$, then $2$ and $n-1$ in set $B$, then $3$ and $n-2$ in $A$, etc..

My algorithm gives correct result if $n$ is divisible $4$, but when it is not divisible by $4$ it will return that the difference between the sets is bigger than it actually is, how can we divide the numbers optimally.

$\endgroup$
2
$\begingroup$

It turns out that the strategy depends on $n$ mod $4$.

To see why, one computes the total sum of all these numbers, which is $n(n+1)/2$. The parity of this sum depends on $n$ mod $4$: if $n$ is congruent to $0$ or $3$ mod $4$, the total sum is even; otherwise the total sum is odd.

When the total sum is odd, it is not possible to divide the set into two parts with equal sums. The minimum difference you can expect is therefore $1$.


If $n = 0$ mod $4$: you already figured out how to do that.

If $n = 1$ mod $4$: divide $2, \cdots, n$ using your strategy, and add the extra $1$ to any side. This achieves the minimum difference $1$.

If $n = 2$ mod $4$: divide $3, \cdots, n$ using your strategy, and add the extra $1$ and $2$ to each side to get the minimum difference $1$.

If $n = 3$ mod $4$: divide $4, \cdots, n$ using your strategy, and add $1$ and $2$ to one side, and $3$ to the other side to get the minimum difference $0$.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.