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.
SolutionIn this problem, we use 2 pointers, one runs from the 0, one runs backward.
- public class Solution {
- public int maxArea(int[] height) {
- //we assume the array height.length > 0
- int max = 0;
- int area;
- for(int i=0, j=height.length-1; i<j;){
- if(height[i] > height[j]){
- area = (j-i) * height[j];
- j--;
- }else {
- area = (j-i) * height[i];
- i++;
- }
- if(area > max) max = area;
- }
- return max;
- }
- }
No comments:
Post a Comment