#11
Medium Algorithms Container with most water
Array Two Pointers Greedy
59.6% acceptance
Jan 12, 2026
33890
2183
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn max_area(height: Vec<i32>) -> i32 {
let mut left = 0;
let mut right = height.len() - 1;
let mut max_area = 0;
while left < right {
// Calculate current area
let width = (right - left) as i32;
let current_height = height[left].min(height[right]);
let current_area = width * current_height;
// Update max area
max_area = max_area.max(current_area);
// Move the pointer with smaller height
if height[left] < height[right] {
left += 1;
} else {
right -= 1;
}
}
max_area
}
}