Container With Most Water
Problem
Given n
non-negative integers a1, a2, ..., an
, where each represents a point at coordinate (i, ai)
. n
vertical lines are drawn such that the two endpoints of the line i
is at (i, ai)
and (i, 0)
. Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
Notice that you may not slant the container.

Solution
class Solution:
def maxArea(self, height: List[int]) -> int:
maxArea = float("-inf")
i = 0
j = len(height) - 1
while i < j:
thisArea = min(height[i], height[j]) * (j-i)
maxArea = max(maxArea, thisArea)
if height[i] < height[j]:
i+=1
else:
j-=1
return maxArea
#Two pointer approach: The two pointer approach can
#be used as we can set both pointers at the end of the
#array and move either pointer forward depending on
#whether ai or aj is the minimum
#Two pointer is the best approach since we need to
#calculate the width between two points
Last updated
Was this helpful?