LeetCode ** 561. Array Partition I
来源:互联网 发布:自制相册软件下载 编辑:程序博客网 时间:2024/06/05 18:16
这个题目意思是把一个2N大小的数组分成N个组,每个组两个数,然后把N个组中小的那个数累加,得到的累加和最大的既为本题的解。
在solution中,本题提供了一个很棒的回答。
Let me try to prove the algorithm...
- Assume in each pair
i
,bi >= ai
. - Denote
Sm = min(a1, b1) + min(a2, b2) + ... + min(an, bn)
. The biggestSm
is the answer of this problem. Given1
,Sm = a1 + a2 + ... + an
. - Denote
Sa = a1 + b1 + a2 + b2 + ... + an + bn
.Sa
is constant for a given input. - Denote
di = |ai - bi|
. Given1
,di = bi - ai
. DenoteSd = d1 + d2 + ... + dn
. - So
Sa = a1 + a1 + d1 + a2 + a2 + d2 + ... + an + an + di = 2Sm + Sd
=>Sm = (Sa - Sd) / 2
. To get the maxSm
, givenSa
is constant, we need to makeSd
as small as possible. - So this problem becomes finding pairs in an array that makes sum of
di
(distance betweenai
andbi
) as small as possible. Apparently, sum of these distances of adjacent elements is the smallest. If that's not intuitive enough, see attached picture. Case 1 has the smallestSd
.
class Solution {public: int arrayPairSum(vector<int>& nums) { sort(nums.begin(), nums.end()); int sum = 0; for (int i = 0; i < nums.size(); sum += nums[i], i += 2); return sum; }};
阅读全文
1 0
- LeetCode 561. Array Partition I
- LeetCode 561. Array Partition I
- [LeetCode]561. Array Partition I
- leetcode 561. Array Partition I
- LeetCode 561. Array Partition I
- Leetcode 561. Array Partition I
- [leetcode]561. Array Partition I
- LeetCode 561. Array Partition I
- LeetCode: 561. Array Partition I
- LeetCode 561. Array Partition I
- LeetCode: 561. Array Partition I
- LeetCode 561. Array Partition I
- LeetCode ** 561. Array Partition I
- leetcode.561.Array Partition I
- 【leetcode】561. Array Partition I
- [LeetCode]561.Array Partition I
- [leetcode]561. Array Partition I
- Leetcode 561.Array Partition I
- 对称的二叉树(Java实现)
- Spring之二,基础深入,理解动态代理
- 以两军问题为背景来演绎Basic Paxos
- 生成GUID算法
- .net根据视频地址获取视频信息
- LeetCode ** 561. Array Partition I
- C# 调用目标异常
- 不同坐标系之间的转换
- Java实现-最长公共前缀
- simditor 限制图片格式 和 上传图片过慢
- Tensorflow MNIST for Android
- 接口请求特殊字符
- TD-LTE RRC连接重建-理论分析
- volley框架的使用