← Daily Logs
LeetCode 11

Container With Most Water

MediumJun 26, 2026arraytwo pointers

Two pointers from both ends: measure the area, move whichever line is shorter inward, and keep the maximum.

The problem

You're given an integer array `height` of length `n`, where line `i` runs from `(i, 0)` to `(i, height[i])`. Pick two lines that, together with the x-axis, hold the most water and return that maximum area.

The container can't be slanted, so the water it holds is the shorter of the two heights times the distance between the lines.

The approach

My idea is to use the two-pointer approach: start `l` at 0 and `r` at the last index. At each step I compute the area between them — `(r - l) * min(height[l], height[r])` — and keep a running maximum in `result`.

Then I move a pointer inward: if `height[l] < height[r]` I increment `l`, otherwise I decrement `r`. I'm always moving away from the shorter line, since that's the one capping the area. The loop runs while `l < r`, and at the end `result` holds the answer.

The solution

js
/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function(height) {
    let result = 0
    let[l,r] = [0,height.length-1]
    while(l<r){
        const area = (r-l)*Math.min(height[l], height[r])
        if(height[l]<height[r]){
            l++
        }
        else {
            r--
        }
        result= Math.max(result,area)
    }
    return result
};

Time O(n)Space O(1)

All entries