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.
Example
Solution 1: brute force
Time Complexity: O(n^2), Space Complexity: O(1)
class Solution {
public int maxArea(int[] height) {
int area = 0;
for(int i = 0; i < height.length; i++)
for(int j = i+1; j < height.length;j++) {
int temp = (j-i)*Math.min(height[i],height[j]);
if(area < temp)
area = temp;
}
return area;
}
}
==Solution 2: ==
Time Complexity: O(n), Space Complexity: O(1)
Consideration:
- we use two pointers to start from the left end and right end of height, since at the beginning, their difference is the biggest
- In each iteration, we calculate the area between the two pointers and compare it with the max. Afterward, we change the pointer which has a shorter height.
class Solution {
public int maxArea(int[] height) {
int max = 0;
int left = 0;
int right = height.length-1;
while(left < right) {
max = Math.max(max, (right-left)*Math.min(height[left],height[right]));
if(height[left] < height[right])
left++;
else
right--;
}
return max;
}
}