1. 程式人生 > >【LeetCode】11. 盛最多水的容器(Container With Most Water)

【LeetCode】11. 盛最多水的容器(Container With Most Water)

英文練習 | 中文練習

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


示例:

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

解題思路: 兩線段之間形成的區域總是會受到其中較短那條長度的限制,同時,兩線段距離越遠,得到的面積就越大。使用兩個指標,一個放在開始,一個放在末尾,更新儲存的最大面積,將指向較短線段的指標向較長線段那端移動一步。

public int maxArea(int[] height) {
    int start = 0,end = height.length - 1;
    int maxArea = 0;
    while(end > start){
        maxArea = Math.max(maxArea, Math.min(height[start], height[end]) * (end - start));
        if(height[start] > height[end]) end--;
        else start++;
    }
    return
maxArea; }