์•Œ๊ณ ๋ฆฌ์ฆ˜๐Ÿฅš/๋ฌธ์ œํ’€์ด (Python)

[LeetCode] 561. array_partition_i (Easy) 2023/5/2

๐Ÿช„ํ•˜๋ฃจ๐Ÿช„ 2023. 5. 2. 08:52
728x90
๋ฌธ์ œ ์ œ๋ชฉ ์ •๋‹ต๋ฅ  ๋‚œ์ด๋„
561. array-partition-i 77.3% Easy
 

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

 

๋ฌธ์ œ์š”์•ฝ

2n ๊ฐœ์˜ ์ •์ˆ˜ํ˜• ๋ฐฐ์—ด์ด ์ฃผ์–ด์งˆ ๋•Œ, ์ž„์˜์˜ ๋‘ ์›์†Œ๋กœ ๊ตฌ์„ฑ๋œ n๊ฐœ์˜ ์Œ์ด ์žˆ๋‹ค๊ณ  ํ•˜์ž, n๊ฐœ์˜ ์Œ์— ๋Œ€ํ•ด ๋‘ ์›์†Œ์ค‘ ์ตœ์†Ÿ๊ฐ’์˜ ํ•ฉ์˜ ์ตœ๋Œ€๋ฅผ ๊ตฌํ•˜์—ฌ๋ผ

์กฐ๊ฑด 1) 2n๊ฐœ์˜ ์ •์ˆ˜ ์ˆซ์ž ๋ฐฐ์—ด์ด ์ฃผ์–ด์ง„๋‹ค

 

 

ํ’€์ด

 

Step1. ๋ฐฐ์—ด์„ ์ •๋ ฌ -> sort() ํ•จ์ˆ˜

 

Step2. ํ™€์ˆ˜๋ฒˆ์งธ ์›์†Œ์˜ ํ•ฉ -> sum(iterable), ์Šฌ๋ผ์ด์‹ฑ ์ด์šฉ

 

 

๊ตฌํ˜„ (278ms)

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