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.java
Note: You may not slant the container.code
假若有容器以下图:
orm
那么他装满水以后必定是这个样子:
blog
能够看出,其从中间到两边必定是呈阶梯状降低的,中间的空缺必定会被水填上的。因此咱们只须要枚举上图中由蓝色组成的矩形便可。队列
开始作的时候居然不会作了。而后问了下学妹,说是单调队列,发现不会写…… 真是忧伤。get
public class Solution { public int maxArea(int[] height) { int l = 0; int r = height.length - 1; int rlt = calcArea(l, r, height); while (l < r) { if (height[l] < height[r]) { l = nextLeftBoard(l, r, height); } else { r = nextRightBoard(l, r, height); } rlt = Math.max(calcArea(l, r, height), rlt); } return rlt; } private int nextLeftBoard(int l, int r, int[] height) { int rlt = l; while (rlt < r && height[rlt] <= height[l]) rlt ++; return rlt; } private int nextRightBoard(int l, int r, int[] height) { int rlt = r; while (l < rlt && height[rlt] <= height[r]) rlt --; return rlt; } private int calcArea(int l, int r, int[] height) { int h = Math.min(height[l], height[r]); return (r-l) * h; } }