본문 바로가기

알고리즘

[알고리즘] 배열-배열 파티션 I - Jungyu Ko

문제 출처

 

Array Partition I - LeetCode

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

문제 설명

n개의 페어를 이용한 min(a, b)의 합으로 만들 수 있는 가장 큰 수를 출력하라.

예시

문제 풀이

class Solution:
    def arrayPairSum(self, nums: List[int]) -> int:
        sorted_nums = sorted(nums)      # 입력 배열을 정렬
        
        ans = 0                                     # 정답 ans 초기값 설정
        for i in range(0, len(sorted_nums), 2):     # 정렬된 배열을 2칸씩 점프하면서 반복
            ans += sorted_nums[i]                   # 정답 ans에 홀수 번째 값을 추가
        # ans = sum(sorted_nums[::2])       # 위의 3줄을 이와같이 한줄로 표현가능
        return ans