Container With Most Water


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


Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.


Two Pointer Approach

class Solution {
    public int maxArea(int[] height) {
        if(height == null || height.length == 0){
            return 0;
        int l = 0;
        int r = height.length -1;
        int max_area = 0;
        while( l < r){
            int h = Math.min(height[l], height[r]);
            int w = (r-l);
            int cur_area = (h * w);
            max_area = Math.max(cur_area, max_area);
            if(height[l] < height[r]){
        return max_area;

Complexity Analysis

  • Time Complexity : O(n). Single pass.
  • Space Complexity : O(1). Constant space is used.

Categories: Array

Tagged as: , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s