Skip to problem
←

Tug of War

Hard 0 attempts

Partition all entries of arr into two groups whose sums have the smallest possible absolute difference.

One group must contain exactly floor(n / 2) entries; the other contains the remaining entries. For even n the sizes are equal; for odd n they differ by one. Values may be negative, zero, or repeated. Each input position must belong to exactly one group.

Return an object:

  • minDiff: the minimum absolute difference between the two sums.
  • bestSubset: the values in an optimal group of size floor(n / 2), not their indices.

Any optimal subset and any ordering of its values are accepted. Respect input multiplicities: a value cannot appear more times than it occurs in arr. The other group is implied by the remaining entries. For a one-element input, bestSubset is empty.

Function contract

Implement tugOfWar(arr).

Output: Return {minDiff, bestSubset}, where minDiff is the minimum absolute difference between group sums and bestSubset contains floor(arr.length / 2) input values. Any optimal subset is accepted.

Example 1

Input
arr = [1,2,3,4]
Output
{"minDiff":0,"bestSubset":[1,4]}

Example 2

Input
arr = [1]
Output
{"minDiff":1,"bestSubset":[]}
Constraints
  • 1 <= arr.length <= 20
  • -10^6 <= arr[i] <= 10^6

Each element can belong to either subset. Use backtracking to explore all groups of size floor(n/2) and track the minimum absolute difference between the two subset sums.

javascript
function tugOfWar(arr) {
  const n = arr.length;
  const half = Math.floor(n / 2);
  const totalSum = arr.reduce((a, b) => a + b, 0);
  let minDiff = Infinity;
  let bestSubset = [];

  function backtrack(idx, count, currentSum, chosen) {
    if (count === half) {
      const diff = Math.abs(totalSum - 2 * currentSum);
      if (diff < minDiff) {
        minDiff = diff;
        bestSubset = [...chosen];
      }
      return;
    }
    if (idx >= n || n - idx < half - count) return;

    chosen.push(arr[idx]);
    backtrack(idx + 1, count + 1, currentSum + arr[idx], chosen);
    chosen.pop();
    backtrack(idx + 1, count, currentSum, chosen);
  }

  backtrack(0, 0, 0, []);
  return { minDiff, bestSubset };
}

Time: O(n × 2^n) as a conservative bound including copies of improved subsets Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript