leetcode-11. Container With Most Water

Youngsun Joung·2025년 10월 4일

Leetcode

목록 보기
5/91

1. 문제 소개

11. Container With Most Water

2. 나의 풀이법

이번에는 투 포인터 방식으로 풀었다.
높이와 길이만 따져서 풀면 되는 방식이다.

class Solution:
    def maxArea(self, height: List[int]) -> int:
        n = len(height)
        l, r = 0, n-1
        area = 0
        
        while l < r:
            area = max(area, (r-l) * min(height[l], height[r]))

            if height[l] < height[r]:
                l += 1
            else:
                r -= 1
                
        return area

3. 다른 풀이법

class Solution:
    def maxArea(self, height: List[int]) -> int:
        left = 0
        right = len(height) - 1
        max_area = 0
        while left < right:
            if height[left] < height[right]:
                area = height[left] * (right - left)
                left += 1
            else:
                area = height[right] * (right - left)
                right -= 1
            if max_area < area:
                max_area = area
        return max_area

다른 풀이법도 방향성은 같지만, max()가 아니라 if문으로 분기처리를 사용하는 것이 훨씬 빠른 풀이를 보장하는 것으로 보인다.

4. 결론

모두 시간복잡도가 O(n)O(n)으로 최적의 풀이가 되어있다.
다음에는 분기처리를 더 시도해볼까한다.

profile
Junior AI Engineer

0개의 댓글