Link: https://oj.leetcode.com/problems/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 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.
I have done this Q before, but still didn't think of the O(n) solution.
Key to this Q: The water between two lines is determined by the shorter line.
Approach I: O(n^2) solution. Time Limit Exceeded.
public class Solution {
public int maxArea(int[] height) {
int maxA = 0;
for(int i = 0; i < height.length; i++){
for(int j = i+1; j < height.length; j++){
maxA = Math.max(maxA, (j-i)*Math.min(height[j], height[i]));
}
}
return maxA;
}
}
Approach II: Greedy
Create two pointers from begin and end. Always move the shorter boundary, since the water is determined by the shorter boundary
Time: O(n), Space: O(1)
public class Solution {
public int maxArea(int[] height) {
int l = 0;
int r = height.length -1;
int maxA = 0;
while(l < r){
maxA = Math.max(maxA, (r - l) * Math.min(height[l], height[r]));
if(height[l] < height[r]){
l++;
}
else{
r--;
}
}
return maxA;
}
}
相关题目:
- Trapping Rain Water(2.1.15, to link)
- Largest Rectangle in Histogram (4.1.3)