SDE & MLE Prep

11. Container With Most Water

Problem

height[i] is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that area: (distance between them) × (the shorter height).

Example: [1,8,6,2,5,4,8,3,7] → 49 (lines at x = 1 and x = 8: 7 × 7)

Constraints: n ≤ 10⁵.

Area = min(h[l], h[r]) * (r - l). Moving the taller side can never help (width shrinks, height capped by the shorter one), so always move the shorter side.

h: 1 8 6 2 5 4 8 3 7
     l             r     min(8,7)*7 = 49  (best)

Complexity: O(n) time, O(1) space.

class Solution:
    def maxArea(self, height: List[int]) -> int:
        l, r, best = 0, len(height) - 1, 0
        while l < r:
            best = max(best, min(height[l], height[r]) * (r - l))
            if height[l] < height[r]:
                l += 1
            else:
                r -= 1
        return best