Note: You may not slant the container.
---
Solution: Start from both ends of the container. Keep track of the maximum area. If the left end is shorter than the right end, move the left end by one step right. Else move the right end by one step left. When you are done, return the maximum area that we have seen so far.
public class Solution {
public int maxArea(int[] height) {
int max = 0;
int left = 0;
int right = height.length - 1;
while (left < right) {
int area = (right - left) * Math.min(height[left], height[right]);
max = Math.max(max, area);
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return max;
}
}
No comments:
Post a Comment