본문 바로가기

Algorithm/Sorting

(C++) - LeetCode (easy) 561. Array Partition

반응형

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

 

Array Partition - LeetCode

Can you solve this real interview question? Array Partition - 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.

leetcode.com

정렬 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. 오름차순으로 nums를 정렬해줍니다.2. 정답을 반환할 변수 sum을 선언 후 0으로 초기화해줍니다.

📔 풀이과정

nums의 원소 크기는 짝수이므로 2씩 증가하는 for loop를 수행합니다.

(i, i+1) 에서 오름차순으로 정렬되었으므로 i가 더 작다는 명제가 성립합니다. 매 loop별 nums[i]를 sum에 누적해 더해줍니다.

📔 정답 출력 | 반환

sum을 반환합니다.


📕 Code

📔 C++

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

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.