This is a creation in Article, where the information may have evolved or changed.
Topic
Given an array of 2n integers, your task was to group these integers into n pairs of integer, say (A1, B1), (A2, B2), ..., (a N, BN) which makes sum of min (AI, bi) for all I from 1 to n as large as possible.
topic: Given a 2n ( even ) length of an array, divided into n groups, return the sum of the smaller values in each group, so that the sum as large as possible Example 1:
Input: [1,4,3,2]output:4explanation:n is 2, and the maximum sum of pairs is 4.
Note:
n is a positive integer, which are in the range of [1, 10000].
All the integers in the array would be in the range of [-10000, 10000].
Ideas:
First, the adjacent two numbers are divided into a group, each group of smaller numbers on the left, sum can be
Algorithm Analysis: view the English version, click above
Assume for each pair of I,bi >= AI.
Define SM = min (a1,b1) + min (a2,b2) + ... + min (an,bn). The biggest SM is the answer to this question. Because bi >= ai,sm = a1 + A2 + ... + an.
Define SA = a1 + b1 + a2 + b2 + ... + an + bn. For a given input, the SA is a constant.
Define DI = | Ai-bi |. Because bi >= ai,di = bi-ai, bi = ai+di.
Define SD = D1 + d2 + ... + DN.
So Sa = A1 + (a1 + D1) + A2 + (A2 + D2) + ... + A + (an + di) = 2Sm + Sd, so sm = (SA-SD)/2. To get the largest SM, the given SA is constant and needs to make the SD as small as possible.
So the problem is to find the smallest possible pair in the array that makes Di (the distance between AI and bi). Obviously, the sum of these distances of neighboring elements is minimal.
Code
Arraypartition.go
package _561_Array_Partition1import "sort"func ArrayPairSum(nums []int) (minPairSum int) { sort.Ints(nums) for k, v := range nums { if 0 == k%2 { minPairSum += v } } return minPairSum}
Test code
Arraypartition_test.go
The package _561_array_partition1import "Testing" func test_arraypairsum (t *testing. T) {input: = []int{1,4,3,2} sum: = Arraypairsum (Input) if 4 = = sum {T.LOGF ("pass")} else {T. Errorf ("Fail, want 4, get%+v\n", Sum)}}