본문 바로가기
알고리즘

array partition

by irerin07 2023. 9. 30.
728x90

https://leetcode.com/problems/array-partition/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

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
Explanation: All possible pairings (ignoring the ordering of elements) are:
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
So the maximum possible sum is 4.

Example 2:

Input: nums = [6,2,6,5,1,2]
Output: 9
Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.

 

Constraints:

  • 1 <= n <= 104
  • nums.length == 2 * n
  • -104 <= nums[i] <= 104
class Solution {
    public int arrayPairSum(int[] nums) {
        int max = 0;
        
        Arrays.sort(nums);
        
        for(int i = 0;i<nums.length;i = i+2){
            max = max + Math.min(nums[i],nums[i+1]);
        }
        
        return max;
    }
}

배열을 오름차순으로 정렬하여 짝을 지어준 다음 각 페어에서 가장 작은 수를 골라 더하는 식으로 풀었음.

그런데 다시 생각해보니 애초에 오름차순으로 정렬이 된 상태라서 Math.min()을 쓸 필요 없이 i번째 원소들끼리 더해주면 된다는 것을 깨달음.

class Solution {
    public int arrayPairSum(int[] nums) {
        int sum = 0;
        
        Arrays.sort(nums);
            
        for(int i=0; i<nums.length; i=i+2) 
            sum += nums[i];
        
        return sum;
    }
}

짜잔

728x90

'알고리즘' 카테고리의 다른 글

[LeetCode] 101. Symmetric Tree  (0) 2023.12.05
[LeetCode] 100. Same Tree  (0) 2023.12.04
Leet Code 412  (0) 2023.07.25
Leet Code 1672  (0) 2023.07.25
Leet Code 1480  (0) 2023.07.25