Skip to content

Commit 9705306

Browse files
committed
solve(w06): 11. Container With Most Water
1 parent 993ff07 commit 9705306

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# https://leetcode.com/problems/container-with-most-water/
2+
3+
from typing import List
4+
5+
class Solution:
6+
def maxArea(self, height: List[int]) -> int:
7+
"""
8+
[Complexity]
9+
- TC: O(n)
10+
- SC: O(1)
11+
12+
[Approach]
13+
양끝에서부터 범위를 좁히면서 확인하는 two-pointer를 이용한다.
14+
양끝 side 중 더 작은 쪽을 안쪽으로 한 칸 옮기면서 확인하고,
15+
만약 두 side가 길이가 같다면 두 개를 모두 안쪽으로 한 칸 옮긴다.
16+
"""
17+
18+
lo, hi = 0, len(height) - 1
19+
max_amount = 0
20+
21+
while lo < hi:
22+
# 양 끝 side 길이
23+
s1, s2 = height[lo], height[hi]
24+
25+
# max_amount 업데이트
26+
max_amount = max(max_amount, (hi - lo) * min(s1, s2))
27+
28+
# 더 낮은 side를 안쪽으로 한 칸 옮기기
29+
if s1 < s2:
30+
lo += 1
31+
elif s1 > s2:
32+
hi -= 1
33+
# 두 side의 크기가 같다면, 둘다 안쪽으로 한 칸씩 옮기기
34+
else:
35+
lo += 1
36+
hi -= 1
37+
38+
return max_amount

0 commit comments

Comments
 (0)