Container With Most Water

Medium

Topics
ArrayTwo PointersGreedy

Given an integer array height of length n, find two lines that together with the x-axis form a container holding the most water. Return the maximum area.

Example 1

186254837
Bars are wall heights. The shaded rectangle is the best container: its height is the shorter of the two chosen walls and its width is the distance between them.
Input:  height = [1,8,6,2,5,4,8,3,7]
Output: 49

Example 2

11
Input:  height = [1,1]
Output: 1

Constraints

  • 2 <= height.length <= 10^5
  • 0 <= height[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

The area between two lines is width × min(height_left, height_right). Start with the widest possible container (the two ends).

Moving the taller wall inward can never increase the area (the shorter wall still caps the height while width shrinks). So always move the shorter wall, hoping to find a taller one.

Approach

  1. Two pointers at the ends; track the best area.
  2. Compute the current area.
  3. Move the shorter side inward.
  4. Stop when the pointers meet.

Walkthrough

height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
l=0 r=8: area=8*1=8, move l (1<7)
l=1 r=8: area=7*7=49, move r (7<8)
... best stays 49 -> answer 49

Complexity

  • Time — O(n): each step moves a pointer inward once.
  • Space — O(1): two pointers.

Common Pitfalls

  • Move the shorter side inward, never the taller one. Moving the taller side can only keep the height the same or lower it while the width shrinks, so it can never find a bigger area -- flipping that comparison returns 8 instead of 49 on the first example.
  • The area uses min of the two heights, not the height at the pointer being moved. Water is limited by the shorter wall.

Full Solution — all languages

class Solution:
    def maxArea(self, nums):
        lo, hi, best = 0, len(nums) - 1, 0
        while lo < hi:
            best = max(best, (hi - lo) * min(nums[lo], nums[hi]))
            if nums[lo] < nums[hi]:
                lo += 1
            else:
                hi -= 1
        return best
SensAI
Beta
Tap the mic to stop voice mode