← Two Pointers

Container With Most Water

Medium
Python
def max_area(height):
    l,r=0,len(height)-1; best=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
Java
public int maxArea(int[] height){
    int l=0,r=height.length-1,best=0;
    while(l<r){
        best=Math.max(best,Math.min(height[l],height[r])*(r-l));
        if(height[l]<height[r]) l++;
        else r--;
    } return best;
}

Key Insight

Greedy: always move shorter side. max/min vs Math.max/min.

Python → Java Differences

  • max/min vs Math.max/min
  • Greedy two-pointer identical
  • Multi-assign vs three declarations
Python
def max_area(height):
    l,r=0,len(height)-1; best=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
Java
public int maxArea(int[] height){
    int l=0,r=height.length-1,best=0;
    while(l<r){
        best=Math.max(best,Math.min(height[l],height[r])*(r-l));
        if(height[l]<height[r]) l++;
        else r--;
    } return best;
}

Algorithm Steps

1. Calculate area
2. Move shorter inward
3. Track max