资讯动态

【leetcode】leetcode:561. Array Partition I

发布时间:2026/10/23 3:35:33 来源:尧图企业网站定制
问题描述Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), …, (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.Example 1:Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4 min(1, 2) min(3, 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].难度等级简单问题还是很简单的其实就是进行排序每次选相邻两个中较小的数这样大的数字损失的最少。唯一注意的可能就是这里步长为2class Solution { public: int arrayPairSum(vectorint nums) { int sum 0; if(nums.size()1){ sort(nums.begin(), nums.end()); for(int i 0; i nums.size(); i2) sum nums[i]; } return sum; } };恩恩好啦LZ又解决一题O(∩_∩)O哈哈~

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑