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.
Note: You may not slant the container.
給定n個非負的整數a1, a2, ..., an,(i, ai) and (i, 0)分別代表坐標(i, ai)。連接(i, ai) and (i, 0)畫直線,共有n條。找出兩條直線,使得兩條直線與x軸形成的容器能夠盛最多的水。

分析

如果容器盛水最多

  • 矩形面積最大。
  • 盛水量的多少,由兩條垂線中較短的一條決定。
  • 兩條垂線中較短一條盡可能長。

算法解析

如圖所示


算法解析
算法解析

以序列最外面兩條邊形成的面基為起始面積,找出兩條邊中較小的一條,索引加一(i++),原因是找出一條更大的邊來代替較小的邊,以使得整個容器最大。

答案

public class Solution {
    public int maxArea(int[] height) {
        int maxArea = 0, left = 0;
        int right = height.length - 1;
        
        while (left < right) {
            maxArea = Math.max(maxArea, Math.min(height[left], height[right]) * (right - left));//求兩點之間的面積
            if (height[left] < height[right]) {
                left ++;
            } else {
                right--;
            }
        }
        return maxArea;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容