1. 문제
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
2. 접근 방법
nums는 2n개의 value가 들어있고,
각각의 요소들을 쌍으로 만들었을 때 해당하는 쌍의 min 값들의 합이 가장 클 때를 구하는 문제입니다
주어진 예시는
[1, 4, 3, 2]
일 때인데,
이 때 답은 4인데요
[1, 2], [3, 4]로 쌍을 나누고, 1+3 했을 때 합이 가장 크다는 것을 알 수 있습니다
그래서 정렬을 하고 2개씩 쌍을 이루게끔하고 최소값을 더하면 됩니다.
근ㄷㅔ 2개씩 묶으니까, 슬라이싱을 사용해서 더해줬습니다.
3. 코드
python
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
return sum(sorted(nums)[::2])
4. 마치며
굿
'Algorithm > Python' 카테고리의 다른 글
[LeetCode] 121. Best Time to Buy and Sell Stock (0) | 2021.06.05 |
---|---|
[LeetCode] 238. Product of Array Except Sell (0) | 2021.06.05 |
[LeetCode] 15. 3Sum (0) | 2021.06.05 |
[LeetCode] 1. Two Sum (0) | 2021.06.04 |
[LeetCode] 5. Longest Palindromic Substring (1) | 2021.06.03 |