1. 程式人生 > 其它 >LeetCode-561. 陣列拆分 I

LeetCode-561. 陣列拆分 I

技術標籤:水題AC記C++LeetCodeleetcodec++

561. 陣列拆分 I

難度簡單243

給定長度為2n的整數陣列nums,你的任務是將這些數分成n對, 例如(a1, b1), (a2, b2), ..., (an, bn),使得從1nmin(ai, bi)總和最大。

返回該最大總和

示例 1:

輸入:nums = [1,4,3,2]
輸出:4
解釋:所有可能的分法(忽略元素順序)為:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
所以最大總和為 4

示例 2:

輸入:nums = [6,2,6,5,1,2]
輸出:9
解釋:最優的分法為 (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9

提示:

  • 1 <= n <= 104
  • nums.length == 2 * n
  • -104<= nums[i] <= 104

排序,貪心

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
	int arrayPairSum(vector<int>& nums) {
		int minVal = 0;
		sort(nums.begin(), nums.end());
		for (int i = 0; i < nums.size(); i = i + 2) {
			minVal += nums[i];
		}
		return minVal;
	}
};


int main() {

	vector<int> v = { 6,2,6,5,1,2 };
	Solution* ps = new Solution();
	cout << ps->arrayPairSum(v) << endl;

	return 0;
}