leetcode 561. Array Partition I 数组元素分组的最小值的和的最大值+直接排序即可

ゞ 浴缸里的玫瑰 2022-06-03 04:16 184阅读 0赞

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].

本题题意很简单,直接排序然后求和即可

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <queue>
  6. #include <stack>
  7. #include <string>
  8. #include <climits>
  9. #include <algorithm>
  10. #include <sstream>
  11. #include <functional>
  12. #include <bitset>
  13. #include <numeric>
  14. #include <cmath>
  15. using namespace std;
  16. class Solution
  17. {
  18. public:
  19. int arrayPairSum(vector<int>& nums)
  20. {
  21. sort(nums.begin(), nums.end());
  22. int sum = 0;
  23. for (int i = 0; i < nums.size(); i++)
  24. {
  25. if (i % 2 == 0)
  26. sum += nums[i];
  27. }
  28. return sum;
  29. }
  30. };

发表评论

表情:
评论列表 (有 0 条评论,184人围观)

还没有评论,来说两句吧...

相关阅读