11 Container with most water

https://leetcode.com/problems/container-with-most-water/

class Solution {
    public int maxArea(int[] height) {
        int n = height.length;
        int start = 0;
        int end = n - 1;
        int leftMax = 0;
        int rightMax = 0;
        int maxWater = 0;
        while (start < end) {
            leftMax = Math.max(leftMax, height[start]);
            rightMax = Math.max(rightMax, height[end]);
            maxWater = Math.max(maxWater, Math.min(leftMax, rightMax) * (end - start));
            if (leftMax < rightMax) {
                start++;
            } else {
                end--;
            }
        }
        return maxWater;
    }
}

喜欢知道解法之后就很好写的题

其实不需要维护leftmax和rightmax,只比较当前的左右值就行

Last updated