Container With Most Water

Problem

Given n non-negative integers representing vertical lines, find two lines that together with the x-axis form a container holding the most water.

Input:  height = [1,8,6,2,5,4,8,3,7]
Output: 49

Python Solution

def max_area(height):
    left, right = 0, len(height) - 1
    best = 0
    while left < right:
        width = right - left
        best = max(best, width * min(height[left], height[right]))
        if height[left] < height[right]:
            left += 1
        else:
            right -= 1
    return best

C++ Solution

int maxArea(vector<int>& height) {
    int left = 0, right = height.size() - 1, best = 0;
    while (left < right) {
        int width = right - left;
        best = max(best, width * min(height[left], height[right]));
        if (height[left] < height[right]) left++;
        else right--;
    }
    return best;
}

Java Solution

class Solution {
    public int maxArea(int[] height) {
        int left = 0, right = height.length - 1, best = 0;
        while (left < right) {
            int width = right - left;
            best = Math.max(best, width * Math.min(height[left], height[right]));
            if (height[left] < height[right]) left++;
            else right--;
        }
        return best;
    }
}

Complexity

Time: O(n) — the pointers close in from both ends, each moving at most n times in total. Space: O(1) — only the pointers and the best area are stored; moving the shorter line is always safe since the taller one can never improve area by moving inward first.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.