Use two pointers to maximize the area between vertical lines.
Use the editor below to measure containers formed by two lines.
Choose which pointer to move
The current area depends on the distance between the pointers and the shorter of their two heights. Decide which pointer can move without discarding a possible improvement.
Submit your implementation when it passes the examples.
Each value in heights represents a vertical line at that index. Choose two lines that hold the greatest amount of water.
Return the maximum area. The area is the shorter height multiplied by the distance between the lines.
2 ≤ heights.length ≤ 100,0000 ≤ heights[i] ≤ 10,000Results appear here after a run.
Start with the widest possible container. Record its area, then move the pointer at the shorter line because keeping that shorter height cannot improve the area after the width shrinks.
For heights [2, 5, 1, 4], the outside walls give 3 × 2 = 6. Keeping the wall of height 2 would only narrow that container. Move left to height 5: the width is now 2 and the limiting height is 4, giving area 8. If the two endpoint heights tie, either one can be discarded after recording its area.
function maxArea(heights) {
let left = 0;
let right = heights.length - 1;
let maximum = 0;
while (left < right) {
const width = right - left;
const height = Math.min(heights[left], heights[right]);
maximum = Math.max(maximum, width * height);
if (heights[left] <= heights[right]) left++;
else right--;
}
return maximum;
}| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(n) | The two pointers move inward across the array once. |
| Auxiliary space | O(1) | The algorithm stores only pointer positions and the best area. |