배열을 오름차순으로 정렬하고, 2개씩 그룹을 만들면 각 그룹의 첫 번째 요소가 그룹에서 작은 값이 되므로, 2개씩 건너뛰면서 합계를 구하면 max합계임
6,2,6,5,1,2 => 1,2,2,5,6,6
class Solution {
public int arrayPairSum(int[] nums) {
Arrays.sort(nums);
int maxSum = 0;
for(int i = 0; i < nums.length; i+=2){
int sum = nums[i];
maxSum += sum;
}
return maxSum;
}
}
'JAVA > leetcode' 카테고리의 다른 글
[LeetCode Medium] BST - Validate Binary Search Tree !! (0) | 2021.08.10 |
---|---|
[LeetCode] Two Sum II - Two Pointer (0) | 2021.08.09 |
[LeetCode] Reverse String - Two-pointer (0) | 2021.08.09 |
[LeetCode] Pascal's Triangle (0) | 2021.08.08 |
[LeetCode] Two Sum (0) | 2021.08.07 |