Container With Most Water

Container With Most Water

One Version - 96ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i, j = 0, len(height) - 1
left = right = water = 0
while i <= j:
left, right = max(left, height[i]), max(right, height[j])
while i <= j and height[i] <= left <= right:
water = max(water, (j - i) * min(left, right))
i += 1
while i <= j and height[j] <= right <= left:
water = max(water, (j - i) * min(left, right))
j -= 1
return water

Another Version - 72ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i, j = 0, len(height) - 1
water = 0
while i <= j:
water = max(water, (j - i) * min(height[i], height[j]))
if height[i] < height[j]:
i += 1
else:
j -= 1
return water

test code

1
2
3
4
In [7]: s = Solution(); t = s.maxArea([1,8,6,2,5,4,8,3,7])
In [8]: t
Out[8]: 49

leet code