Skip to content

Commit 85c2967

Browse files
committed
add solution: container-with-most-water
1 parent c0204ce commit 85c2967

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
'''
2+
# 11. Container With Most Water
3+
4+
use two pointers to find the maximum area.
5+
6+
> **move the shorter line inward:**
7+
> - area is determined by the shorter line.
8+
> - move the shorter line inward => may find a taller line that can increase the area.
9+
10+
## Time and Space Complexity
11+
12+
```
13+
TC: O(n)
14+
SC: O(1)
15+
```
16+
17+
### TC is O(n):
18+
- while loop iterates through the height array once. = O(n)
19+
20+
### SC is O(1):
21+
- using two pointers and max_area variable. = O(1)
22+
'''
23+
24+
class Solution:
25+
def maxArea(self, height: List[int]) -> int:
26+
left = 0
27+
right = len(height) - 1
28+
max_area = 0
29+
30+
while left < right: # TC: O(n)
31+
distance = right - left
32+
current_area = min(height[left], height[right]) * distance
33+
max_area = max(current_area, max_area)
34+
35+
if height[left] < height[right]:
36+
left += 1
37+
else:
38+
right -= 1
39+
40+
return max_area

0 commit comments

Comments
 (0)