LeetCode 11. Container With Most Water



Given n non-negative integers a1a2, …, an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.


First, draw an x, y-axis picture to convert text information.

Then generalize ideas from the picture.

The container is a rectangle. So the amount of the water is determined by the width and height. The container’s width is right – left and height is the minimum value between left line height and right line height.

Video Tutorial

Java Solution

class Solution {
    public int maxArea(int[] height) {
        int maxArea = 0;
        if (height == null) {
            return maxArea;
        int left = 0;
        int right = height.length - 1;
        while (left < right) {
            int area = (right - left) * Math.min(height[left], height[right]);
            maxArea = Math.max(maxArea, area);
            if (height[left] < height[right]) {
            } else {
        return maxArea;
        // Time Complexity : O(n)
        // Space Complexity : O(1)

Leave a Reply

Your email address will not be published. Required fields are marked *