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.
最基础的方法 O(n2),会超时,跟最大直方图略像,但是不一样,最大直方图是至少包括一个完整的柱子,本题是有两个line决定一个面积。
public class Solution { public int maxArea(int[] height) { // Note: The Solution object is instantiated only once and is reused by each test case. Stack<Integer> stack = new Stack<Integer>(); int i = 0; int j = height.length-1; int maxArea = 0; while(i < j){ if(height[i]<height[j]){ maxArea = Math.max(maxArea,height[i]*(j-i)); i++; }else if(height[i]>height[j]){ maxArea = Math.max(maxArea,height[j]*(j-i)); j--; }else{ maxArea = Math.max(maxArea,height[i]*(j-i)); i++; j--; } } return maxArea; } }