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.Example 1:
Input: nums = [1,4,3,2]
Output: 4
Approach
Java
import java.util.Arrays;public class ArrayPartitionI {public static void main(String[] args) {int[] nums = { 1, 4, 3, 2 };System.out.println(arrayPairSum(nums));}static int arrayPairSum(int[] nums) {// sort the arrayArrays.sort(nums);int res = 0;for (int i = 0; i < nums.length; i++) {if (i % 2 == 0)res += nums[i];}return res;}}
C++
#include <bits/stdc++.h>using namespace std;int arrayPairSum(vector<int> &nums){//sort the arraysort(nums.begin(), nums.end());int res = 0;for (int i = 0; i < nums.size(); i++){if (i % 2 == 0)res += nums[i];}return res;}int main(){vector<int> nums = {1, 4, 3, 2};cout << arrayPairSum(nums);return 0;}
No comments:
Post a Comment