<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
'Algorithm > 파이썬 알고리즘 인터뷰 스터디' 카테고리의 다른 글
| [배열] 12 주식을 사고팔기 가장 좋은 시점(Best Time to Buy and Sell Stock) (0) | 2021.08.03 |
|---|---|
| [배열] 11 자신을 제외한 배열의 곱(Product of Array Except Self) (0) | 2021.08.03 |
| [배열] 09 세 수의 합(3Sum) (0) | 2021.08.03 |
| [배열] 08 빗물 트래핑(Trapping Rain Water) ✔ (0) | 2021.08.03 |
| [배열] 07 두 수의 합(Two Sum) ✔ (0) | 2021.08.03 |