11. Container With Most Water

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

  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