본문 바로가기

알고리즘

[투포인터] Container With Most Water - LeetCode Swift

문제 : https://leetcode.com/problems/container-with-most-water/

 

Container With Most Water - 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

 

풀이방법

양쪽 끝에 포인터를 한개씩 둔다음에 모든 Area 중에 제일 큰 Area를 반환한다.

 

코드

class Solution {
    func maxArea(_ height: [Int]) -> Int {
        var startPoint = 0
        var endPoint = height.count - 1
        var area = 0
        
        guard endPoint != 1 else {
            return min(height[startPoint], height[endPoint])
        }
        
        while startPoint < endPoint {
            let width = endPoint - startPoint 
            var newArea = 0
            
              if height[startPoint] < height[endPoint] {
                newArea = width * height[startPoint]
                startPoint += 1
            } else {
                newArea = width * height[endPoint]
                endPoint -= 1
            }
            
             area = max(area, newArea)
        }
        return area
    }
}
반응형