| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 17070
- 정렬
- 2247
- 27448
- 모두의 꿈
- 부분수열의 합2
- 코테
- BFS
- 스펨메일 분류
- dp
- C
- 아니메컵
- lgb
- python
- 코딩
- 백준
- 실질적 약수
- dfs
- 샤논 엔트로피
- 정답코드
- 코딩테스트
- populating next right pointers in each node
- 힙 정렬
- 구현
- 파이썬
- T tree
- 딥러닝
- 코복장
- 다이나믹 프로그래밍
- ps
Archives
- Today
- Total
코딩복습장
LeetCode: Array Partition 본문
728x90
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.
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.
Constraints:
- 1 <= n <= 104
- nums.length == 2 * n
- -104 <= nums[i] <= 104
이 문제는 가장 큰 값이 나오는 pair의 조합을 찾는 문제이다.
풀이 방법은 간단하다.
일단 nums를 정렬한다.(오름차순)
이후 정렬된 list에서 range(len(nums)-2, -1, -2)로 res에 nums[idx]를 더해준다.
어짜피 큰 수는 못들어가기 때문에 큰 수와 그 다음으로 큰 수를 비교하여 가장 큰수와 비교했을 때, 가장 큰 수가 output
으로 나올 수 있도록 만들어 준 것이다.
이 아이디어를 활용하면 문제를 간단하게 풀 수 있게 된다.

구현코드
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0
nums.sort()
for idx in range(len(nums)-2, -1, -2):
res += nums[idx]
return res728x90
'코딩 테스트 > python(파이썬)' 카테고리의 다른 글
| LeetCode: binary-tree-postorder-traversal (0) | 2025.06.10 |
|---|---|
| LeetCode: Binary Tree Preorder Traversal (2) | 2025.06.10 |
| LeetCode: Remove Element (2) | 2025.06.07 |
| 백준: 14891번 톱니바퀴 (0) | 2025.06.06 |
| LeetCode: Longest Common Prefix (0) | 2025.06.03 |
Comments