Container With Most Water

Yeonu Heo 허연우·2024년 3월 26일

알고리즘 문제풀이

목록 보기
23/26

Container With Most Water

[문제]
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

[입력 조건]
n == height.length
2 <= n <= 105
0 <= height[i] <= 104

[내 풀이]

class Solution:
    def maxArea(self, height: List[int]) -> int:
        max_area = 0
        left = 0
        right = len(height) - 1

        while right > left:
            gap = (right - left) * min(height[left], height[right])
            max_area = max(max_area, gap)
            
            if height[left] < height[right]:
                left += 1
            else:
                right -= 1

        return max_area

해결 방법

모든 배열을 순회하는 건 n2라 조금 더 효율적으로 순회하는 방법을 찾아야했다.
left와 right 변수 두개로 끝에서부터 동시에 비교하는 방법으로 구현했다.

[출처]
https://leetcode.com/problems/container-with-most-water

profile
Learn & Travel , 배움을 멈추는 순간 굴러떨어진다

0개의 댓글