11. Container With Most Water
Medium
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.
Note: You may not slant the container and n is at least 2.

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.
Example:
Input: [1,8,6,2,5,4,8,3,7] Output: 49
Note 1 : When you consider a1 and aN, then the area is (N-1) * min(a1, aN). Note 2 : The base (N-1) is the maximum possible.
- This implies that if there was a better solution possible, it will definitely have the Height greater than min(a1, aN).
- We know that, Base min(a1, aN)
This means that we can discard min(a1, aN) from our set and look to solve this problem again from the start. - If a1 < aN, then the problem reduces to solving the same thing for a2, aN.
- Else, it reduces to solving the same thing for a1, aN-1
public int maxArea(int[] height) {
if(height == null || height.length == 0){
return 0;
}
int right = height.length - 1;
int left = 0;
int max = 0;
while(left <= right){
int area = Math.min(height[left], height[right]) * (right - left);
max = Math.max(max, area);
if(height[left] < height[right]){
left++;
}else{
right--;
}
}
return max;
}
Comments
Post a Comment