반응형
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.
Example 1:

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example 2:
Input: height = [1,1]
Output: 1
Constraints:
n == height.length2 <= n <= 1050 <= height[i] <= 104
class Solution:
def maxArea(self, height: List[int]) -> int:
mx = 0
left, right = 0, len(height) - 1
while left < right :
mx = max(mx, (right - left) * min(height[left], height[right]))
if height[left] > height[right] :
right -= 1
else :
left += 1
return mx
이 문제는 오히려 어렵게 생각해서 어렵게 풀었다. 생각보다 간단한 풀이가 될 것이다.
하나만 기억하자. 물을 가장 많이 가두기 위해서는 높이와 너비가 충족되어야 한다.
- 투 포인터를 채택하여 left 와 right 를 양극단에 가져다 놓는다.
- 그러면 신경 쓸 부분은 높이만 신경 쓰면 되기 때문에 양극단에 가져다 놓은 left와 right 중 높이가 높은 단은 가만히 두고 작은 곳만 움직이면 된다. 높이의 결정은 작은 곳이 결정하게 되기 때문이다.
- 가장 많이 가둘 수 있는 물의 양을 체크한 후 갱신해나가면 최대 가둘 수 있는 물의 양을 체크할 수 있다.
반응형
'알고리즘 스터디' 카테고리의 다른 글
| [코드트리/파이썬] 가로등 설치 (1) | 2026.04.26 |
|---|---|
| [Leetcode/파이썬] 104. Maximum Depth of Binary Tree (0) | 2026.04.05 |
| [Leetcode/파이썬] 207. Course Schedule (0) | 2026.04.05 |
| [Leetcode/파이썬] 88. Merge Sorted Array (0) | 2026.04.05 |
| [Leetcode/파이썬] 106. Construct Binary Tree from Inorder and Postorder Traversal (0) | 2026.03.29 |