leetcode : Container With Most Water

Container With Most Waterjava

 

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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 and n is at least 2.orm

 

思路: two pointersblog

兩根指針,分別指向頭尾,若height[i] < height[j], 則i++, 不然j--.  O(n)時間複雜度。get

原理: 木桶原理的特色是取短板。 由於水的最大高度只能到短板,不然會溢出。it

    爲何height[i] < height[j],i++?io

證實: 反證法。ast

      假定height[i] < height[j],  取任意k, 使得 i < k < j。 form

       => (j - i) * height[i]  > (k - i) * min(height[i], height[k])class

       = >  移動j指針,只會獲得比當前更小的容量。 由於 (j - i) >> (k - i), height[i] >= min(height[i], height[k]) 

       =>   所以,若移動i,則有可能獲得比當前更大的容量。

 

public class Solution {
    public int maxArea(int[] height) {
        if(height == null || height.length < 2) {
            return 0;
        }
        
        int i = 0;
        int j = height.length - 1;
        int max = 0;
        
        while(i < j) {
            if(height[i] < height[j]) {
                int tmp = (j - i) * height[i];
                max = Math.max(max,tmp);
                i++;
            } else {
                int tmp = (j - i) * height[j];
                max = Math.max(max,tmp);
                j--;
            }
        }
        return max;
    }
}
相關文章
相關標籤/搜索