LeetCode 11. 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.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;
    }
}
相關文章
相關標籤/搜索