코딩복습장

LeetCode: Array Partition 본문

코딩 테스트/python(파이썬)

LeetCode: Array Partition

코복장 2025. 6. 9. 11:14
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 res
728x90
Comments