본문 바로가기

알고리즘

[투포인터] Minimize Maximum Pair Sum in Array - LeetCode Swift

문제 : https://leetcode.com/problems/minimize-maximum-pair-sum-in-array/

 

Minimize Maximum Pair Sum in Array - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

풀이방법

오름차순으로 정렬후 가운데 인덱스를 구해서 양쪽으로 더한것들 중 제일 큰것을 반환한다.

 

코드

class Solution {
    func minPairSum(_ nums: [Int]) -> Int {
        let SortedNums = nums.sorted(by: <)
        let halfIndex = nums.count/2
        var leftIndex = halfIndex - 1
        var rightIndex = halfIndex
        var max = 0
        
        while leftIndex >= 0 {
            
            if max < (SortedNums[leftIndex] + SortedNums[rightIndex]) {
                max = (SortedNums[leftIndex] + SortedNums[rightIndex])
            }
            
            leftIndex -= 1
            rightIndex += 1
            
        }
        
        return max
    }
}
반응형