# Container With Most Water

- **Canonical ID**: `container-with-most-water`
- **Canonical URL**: https://dsacheatsheet.com/problems/container-with-most-water
- **Difficulty**: medium
- **Patterns**: Two Pointers
- **Version**: 1.0.0 (verified 2026-11-11T21:00:00Z)
- **Original Problem**: https://leetcode.com/problems/container-with-most-water/

## 1. Core Invariant / The Trick

Start with widest container `(l=0, r=n-1)`. Always move the SHORTER wall inward: advancing the taller wall can only shrink width while keeping height bounded by the untouched shorter wall.

## 2. Complexity Bounds & Proof

- **Time Complexity**: `O(N)`
- **Space Complexity**: `O(1)`
- **Proof**: Greedy exchange proof: no pair using the shorter wall with a narrower width can beat the current width.

## 3. Minimal Idiomatic Code

### Python
```python
def maxArea(height: list[int]) -> int:
    l, r = 0, len(height) - 1
    best = 0
    while l < r:
        best = max(best, (r - l) * min(height[l], height[r]))
        if height[l] < height[r]: l += 1
        else: r -= 1
    return best
```

### TypeScript
```typescript
export function maxArea(height: number[]): number {
  let l = 0, r = height.length - 1, best = 0;
  while (l < r) {
    best = Math.max(best, (r - l) * Math.min(height[l], height[r]));
    if (height[l] < height[r]) l++; else r--;
  }
  return best;
}
```

### C++
```cpp
int maxArea(vector<int>& h) {
    int l = 0, r = h.size() - 1, best = 0;
    while (l < r) {
        best = max(best, (r - l) * min(h[l], h[r]));
        h[l] < h[r] ? l++ : r--;
    }
    return best;
}
```

### Java
```java
int maxArea(int[] h) {
    int l = 0, r = h.length - 1, best = 0;
    while (l < r) {
        best = Math.max(best, (r - l) * Math.min(h[l], h[r]));
        if (h[l] < h[r]) l++; else r--;
    }
    return best;
}
```

### Go
```go
func maxArea(h []int) int {
    l, r, best := 0, len(h)-1, 0
    for l < r {
        area := (r - l) * min(h[l], h[r])
        if area > best { best = area }
        if h[l] < h[r] { l++ } else { r-- }
    }
    return best
}
```

## 4. Failure Modes & Interview Follow-ups

### Pitfalls
- Confusing with Trapping Rain Water (this looks at pair extremes only, no bar obstruction subtraction).

### Follow-ups
- Trapping Rain Water calculates cumulative depth across every index.
