LeetCode贪心 数组拆分I
生活随笔
收集整理的這篇文章主要介紹了
LeetCode贪心 数组拆分I
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), …, (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.
思路
這道題要使得各最小值相加最小,就要使得的每一組中的兩數差的絕對值最小。假如一對數字中的差很大,會導致這對數字中較大的數字被舍棄了。因此,只需要把數組進行排序,兩兩循環,累加每對數字中的較小者即可。
代碼
class Solution { public:int arrayPairSum(vector<int>& nums) {sort(nums.begin(), nums.end());int sum = 0;for(int i = 0; i < nums.size(); i += 2){if(nums[i] < nums[i+1])sum += nums[i];else sum += nums[i+1];}return sum;} }; 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的LeetCode贪心 数组拆分I的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 红魔9 Pro挑战器件堆叠极限:首款不凸
- 下一篇: LeetCode贪心 最长回文串