oneby7

2-D Dynamic Programming Knapsack

557. Partition Array Into Two Arrays to Minimize Sum Difference

Hard

You are given an array nums of 2 · n integers. Split it into two groups of exactly n elements each, so that every element goes into exactly one group. The groups do not have to be contiguous.

Return the smallest possible absolute difference between the sum of one group and the sum of the other.

Example 1

Input: nums = [3, 10, 2, 1, 2, 2]

Output: 6

Explanation: Each group must hold three elements. The best split is [10, 1, 2] and [3, 2, 2], with sums 13 and 7. Putting 10 alone against the other five would give equal sums, but the groups would not be the same size.

Example 2

Input: nums = [-8, 5, -3, 4]

Output: 4

Explanation: [-8, 5] sums to −3 and [-3, 4] sums to 1, so the difference is 4. The other two splits give 6 and 20.

Example 3

Input: nums = [6, -6]

Output: 12

Explanation: Each group holds one element, so the only split is [6] and [-6].

Check your understanding

Work out the answer for this input before you write any code.

nums = [2, 2, 2, 6]

Constraints

  • 1 ≤ n ≤ 15
  • nums.length = 2 · n
  • -107 ≤ nums[i] ≤ 107

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.