1. 程式人生 > 實用技巧 >LeetCode 11 盛最多水的容器

LeetCode 11 盛最多水的容器

LeetCode11 盛最多水的容器

題目描述

給你 n 個非負整數 a1,a2,...,an,每個數代表座標中的一個點 (i, ai) 。在座標內畫 n 條垂直線,垂直線 i 的兩個端點分別為 (i, ai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。

說明:你不能傾斜容器,且 n 的值至少為 2。

圖中垂直線代表輸入陣列 [1,8,6,2,5,4,8,3,7]。在此情況下,容器能夠容納水(表示為藍色部分)的最大值為 49。

樣例

輸入:[1,8,6,2,5,4,8,3,7]
輸出:49

演算法分析

題意的簡單理解:選兩個豎條,使得面積最大

貪心的演算法,思路是很簡單的

操作

  • l左指標,r右指標
  • 當前面積 = Math.min(height[l], height[r]) * (r - l)
  • 高度低的,移動,移動後更新max = Max(max, 當前面積)

關於貪心正確的證明可以看小呆呆的題解有提到

時間複雜度

\(O(n)\)

Java程式碼

class Solution {
    public int maxArea(int[] height) {
        int l = 0;
        int r = height.length - 1;
        int res  = 0;
        while( l < r){
            res = Math.max(res, Math.min(height[l], height[r]) * (r - l));
            if(height[l] < height[r]) l++;
            else r--;
        }

        return res;
    }
}