
문제
https://leetcode.com/problems/array-partition/
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
n개의 페어를 이용한 min(a, b)의 합으로 만들 수 있는 가장 큰 수를 출력하는 배열 문제다.
예시
Example 1:
Input: nums = [1,4,3,2]
Output: 4
Explanation: All possible pairings (ignoring the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.
Example 2:
Input: nums = [6,2,6,5,1,2]
Output: 9
Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
풀이
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
nums.sort()
return sum(nums[::2])
- 이 문제는 min(a, b)의 합이 커야 하므로 결국 min(a, b) 값이 커야 한다.
- 오름차순으로 정렬 후 2칸씩 건너뛰는 슬라이싱[::2]을 활용해 값을 더해주면 된다.
참조 : 박상길, 파이썬 알고리즘 인터뷰 https://github.com/onlybooks/algorithm-interview
'알고리즘' 카테고리의 다른 글
| [리트코드(LeetCode)] 771번 Jewels and Stones (0) | 2024.01.05 |
|---|---|
| [리트코드(LeetCode)] 225번, 232번 Stack, Queue (1) | 2024.01.05 |
| [리트코드(LeetCode)] 15번 3Sum (2) | 2024.01.04 |
| [리트코드(LeetCode)] 5번 Longest Palindromic Substring (1) | 2024.01.04 |
| [리트코드(LeetCode)] 49번 Group Anagrams (0) | 2024.01.04 |