Container With Most Water

Monisha Mathew
1 min readApr 7, 2019

--

Question: 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 line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Well, for a better understanding, you might want to check out the full question here.

Approach: The solution is borrowed from here. So, let’s quickly dive into the code —

//Approach 1
//Runtime: 2ms
//Memory usage: 40.9MB
class Solution {
public int maxArea(int[] height) {
int length = height.length;
int max = 0;
int area = 0;
for(int left = 0, right = length - 1; left<right;){
area = (right-left) * Math.min(height[left], height[right]);
max = Math.max(max, area);
if(height[left]<height[right]){
left++;
} else {
right--;
}
}
return max;
}
}

Find more posts here.

Cheers & Chao!

--

--