PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#BS0000486. Chia mảng thành hai nhóm có độ chênh lệch tổng nhỏ nhất (Partition Array Into Two Arrays to Minimize Sum Difference)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Chia mảng thành hai nhóm có độ chênh lệch tổng nhỏ nhất (Partition Array Into Two Arrays to Minimize Sum Difference)

Partition Array Into Two Arrays to Minimize Sum Difference

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

An array contains 2n2n integers a1,a2,…,a2na_1,a_2,\ldots,a_{2n}. Divide all its elements into two groups AA and BB, each containing exactly nn elements.

Each position in the array must be assigned to exactly one group, even when several positions hold equal values. Elements of a group need not be consecutive in the original array. The value of a group is the sum of its elements.

Among all valid partitions, find the minimum absolute difference between the two sums:

∣∑x∈Ax−∑x∈Bx∣.\left|\sum_{x\in A}x-\sum_{x\in B}x\right|.

Input

  • The first line contains an integer nn, the number of elements in each group after partitioning.
  • The second line contains exactly 2n2n integers a1,a2,…,a2na_1,a_2,\ldots,a_{2n} in their original order.

Output

Print a nonnegative integer: the minimum absolute difference between the sums of the two groups of exactly nn elements each.

Subtasks

  • Subtask 1 (20 points): 1≤n≤91\le n\le 9; −107≤ai≤107-10^7\le a_i\le 10^7 for every 1≤i≤2n1\le i\le 2n; the array has exactly 2n2n elements.
  • Subtask 2 (30 points): 1≤n≤151\le n\le 15; −100≤ai≤100-100\le a_i\le 100 for every 1≤i≤2n1\le i\le 2n; the array has exactly 2n2n elements.
  • Subtask 3 (50 points): 1≤n≤151\le n\le 15; −107≤ai≤107-10^7\le a_i\le 10^7 for every 1≤i≤2n1\le i\le 2n; the array has exactly 2n2n elements.

Examples

Input 1

2
3 9 7 3

Output 1

2

Explanation 1

Here n=2n=2, so each group contains two elements. The first two positions give group AA a sum of 3+9=123+9=12. The remaining positions give group BB a sum of 7+3=107+3=10. The difference is ∣12−10∣=2|12-10|=2.

The total is 2222. A difference of 00 would require both sums to be 1111, but the possible sums of two distinct positions are 6,10,12,166,10,12,16. Every difference is even, so no difference smaller than 22 is possible.

Illustration of the two groups

Input 2

1
-36 36

Output 2

72

Explanation 2

Since n=1n=1, each group takes one element. The sums are −36-36 and 3636, giving ∣−36−36∣=72|-36-36|=72. Exchanging the group labels does not affect the result.

Input 3

3
2 -1 0 4 -2 -9

Output 3

0

Explanation 3

There are six elements and each group needs three. Choose 2,4,−92,4,-9 for the first group, with sum 2+4−9=−32+4-9=-3. The remaining elements −1,0,−2-1,0,-2 also sum to −3-3. Equal sums give a difference of 00, the smallest possible value.