Container with Most Water

Array
Medium

Approach

Diagrams

Analysis

Time

O(n)

Space

O(1)
class Solution:
    def maxArea(self, heights):
        leftPointer = 0
        rightPointer = len(heights) - 1

        maxAreaSoFar = 0

        while leftPointer < rightPointer:
            heightOfLeftLine = heights[leftPointer]
            heightOfRightLine = heights[rightPointer]

            currentWidth = rightPointer - leftPointer
            currentHeight = min(heightOfLeftLine, heightOfRightLine)

            areaRightNow = currentWidth * currentHeight
            maxAreaSoFar = max(maxAreaSoFar, areaRightNow)

            # Move "shorter" pointer towards "taller" pointer
            if heightOfLeftLine < heightOfRightLine:
                leftPointer += 1

            else:
                rightPointer -= 1

        return maxAreaSoFar

Learn

#Two Pointers

Videos