Given an array of 2n integers, your task is to groupthese integers into n pairsof integer, say (a1, b1), (a2, b2),..., (an, bn) which makes sum of min(ai, bi) forall i from 1 to n as large as possible.
Example1:
Input: [1,4,3,2]
Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4.
Note:
- n is a positive integer, which is in the range of [1, 10000].
- All the integers in the array will be in the range of [-10000, 10000].
这个题目的意思就是给你一个偶数项的数组,然后把两个数分一组,找出每组中最下的数,然后把这些最小的数加起来,还要让总和尽可能的大.
其实稍微想一想就会发现,想要总和最大,就把数组排好续之后,每两个连续的分一组,然后把每组中的第一个元素全部累加起来就好了,
实际上就是把数组中从下标为0的元素开始的所有偶数下标都加在一起就是最大的了,如果找最小的和,就把数组排好序以后把前半部分元素加在一起就是最小的和了.
具体操作就分这两个步骤:
1.给数组排序
2.累加偶数项和
代码如下:
int arrayPairSum(int* nums, intnumsSize) {
int sum=0;
int i,t,p;
for (i =1; i <numsSize; ++i)
{
t=nums[i];
p=i-1;
while(p>=0 && t<nums[p])
{
nums[p+1]=nums[p];
p--;
}
nums[p+1]=t;
}
for(i=0;i<numsSize;i=i+2)
sum+= nums[i];
return sum;
}
最开始我用的冒泡排序,没有通过,后来用了选择排序,