838. Halves Close in Sum

A relay club has 2n runners and nums[i] is the signed score adjustment of runner i (negative means a penalty). The coach must form exactly two teams of n runners each, every runner belonging to exactly one team.

Return the smallest possible absolute difference between the two team totals. The array length is always even, and the teams are unordered, so only the difference matters.

Trying every split is far too slow once n reaches 20. Aim to split the array in two halves, enumerate the choices in each half separately and combine them, giving roughly time O(2^n * n) and space O(2^n).

Example 1

Input:
nums = [14,-3,8,21,-9,5]
Output:
2
Explanation:

Groups {21, 5, -9} (sum 17) and {14, -3, 8} (sum 19) differ by 2, and no split of these six values reaches a difference of 0.

Example 2

Input:
nums = [40,-25,10,10]
Output:
5
Explanation:

Pairing 40 with -25 gives 15 and the other pair gives 20, a difference of 5; every other split is much worse.

Constraints

2 ≤ nums.length ≤ 40 and nums.length is even

-107 ≤ nums[i] ≤ 107

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(2^n * n)
Space
O(2^n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…