383. Container With Most Water

最后更新

一刷。

双指针夹逼。

容器的高度受限于较小的边,夹的时候底在变小,所以移动较大的边没有意义,最终高度还是小的那边;只能尝试移动小的那个边。

public class Solution {
    public int maxArea(int[] heights) {
        // write your code here
        if (heights.length == 0) return 0;
        int max = 0;
        int l = 0;
        int r = heights.length - 1;
        while (l < r) {
            int base = r - l;
            int height = Math.min(heights[l], heights[r]);
            max = Math.max(max, base * height);
            
            if (heights[l] < heights[r]) {
                l ++;
            } else {
                r --;
            }
        }
        
        return max;
    }
}
原文地址:https://www.cnblogs.com/reboot329/p/6216531.html