11. Container With Most Water

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

  1. brute force

i 對 其他所有, 一一球出面積, 取 max

class Solution {
    public int maxArea(int[] height) {
        int max = 0;
        for (int i = 0; i < height.length; i++) {
            for (int j = i+1; j < height.length; j++) {
                max = Math.max(max, (j - i) * Math.min(height[i], height[j]));
            }
        }
        return max;
    }
}

2. two points

2者其一如果高是小的話, 要往中間逼近, 為了找更大的

j - i + 1 是因為前面有做 i++, j--, 無論哪個, 都是+1

class Solution {
    // 2 two points
    public int maxArea(int[] height) {
        int i = 0;
        int j = height.length - 1;
        int maxArea = 0;
        while (i < j) {
            int minHeight = height[i] < height[j] ? height[i++] : height[j--];
            maxArea = Math.max(maxArea, (j - i + 1)*minHeight);
        }
        return maxArea;
    }
}

Last updated