본문 바로가기

Algorithm/파이썬 알고리즘 인터뷰 스터디

[배열] 10 배열 파티션 I(Array Partition I)

<LeetCode 문제>

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

 

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)의 합으로 만들 수 있는 가장 큰 수를 출력하는 문제입니다.

<풀이>

두 페어씩 묶어서 최대한 크게 만들어야 하는데, 예시를 살펴보면 모두 정렬후에 앞에서부터 2개씩 묶습니다.

따라서 짝수index(0,2,4,...)인 값들의 합이 문제의 답입니다.(정렬된 상태에서 짝수 번째에 항상 작은 값이 위치하므로)

class Solution:
    def arrayPairSum(self, nums: List[int]) -> int:
        nums.sort()
        return sum(nums[::2])

 

이를 sorted()를 이용해 한줄로 적을 수도 있습니다.

class Solution:
    def arrayPairSum(self, nums: List[int]) -> int:
        return sum(sorted(nums)[::2])

 

슬라이싱을 통해 성능 또한 매우 좋은 모습을 실행 시간을 통해 확인할 수 있습니다.

 

<학습내용>

1. X

<학습이 필요한 내용>

1. X

 

https://github.com/HoYoungChun/Algorithm_PS/blob/master/Python_Study/07_array/LC_561.py

 

GitHub - HoYoungChun/Algorithm_PS: Baekjoon Online Judge, Programmers, LeetCode problem solving by Python, C++

Baekjoon Online Judge, Programmers, LeetCode problem solving by Python, C++ - GitHub - HoYoungChun/Algorithm_PS: Baekjoon Online Judge, Programmers, LeetCode problem solving by Python, C++

github.com