Tech for good

[Leetcode/Sort, Greedy] 561. Array Partition 본문

IT/Computer Science

[Leetcode/Sort, Greedy] 561. Array Partition

Diana Kang 2025. 5. 2. 21:59

 

 

class Solution:
    def arrayPairSum(self, nums: List[int]) -> int:
        nums.sort()
        return sum(nums[::2])

🧠 Greedy Strategy:

To maximize the sum of the minimums of all n pairs, you should:

  • Sort the array
  • Always pair adjacent elements: (nums[0], nums[1]), (nums[2], nums[3]), ...

This ensures that the smaller number in each pair is as large as possible — which directly contributes to the final sum.