Posts Container With Most Water
Post
Cancel

Container With Most Water

This question is part of NeetCode150 series.

Problem Description

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.

leetcode

Solution

Two Pointer Approach

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
    public int maxArea(int[] height) {
        
        int max = 0;
        
        int i=0;
        int j=height.length-1;
        
        while(i<j){
            
            int amount =(j-i)*(Math.min(height[i], height[j]));
            max = Math.max(max, amount);
            
            if(height[i] > height[j]){
                j--;
            }else{
                i++;
            }
            
        }
        
        return max;
        
    }
}
This post is licensed under CC BY 4.0 by the author.