[Leetcode]11. Container With Most Water

2024. 7. 29. 21:13java/javaAlgorithm

1. problem : 

https://leetcode.com/problems/container-with-most-water/?envType=study-plan-v2&envId=leetcode-75

 

2. solution 1 :

class Solution {
    public int maxArea(int[] height) {
        int n = height.length;
        int i = 0;
        int j = n - 1;
        int maxWater = 0;
        while (i < j) {
            int len = Math.min(height[i],height[j]);
            int waterArea = (j-i) * len;
            if (maxWater < waterArea) {
                maxWater = waterArea;
            }
            while (height[i] <= len && i < j) i++;
            while (height[j] <= len && i < j) j--;
        }
        return maxWater;    
    }
}

이 문제는 큰 스틱은 그대로 두고, 작은 스틱을 옮기면서 최댓값은 갱신하는 문제다. 사실, 발상자체가 이해가 되지 않는다. 

왜? 작은 스틱을 옮겨야 하는가? 이게 모든 경우에 적용할 수 있는가?라는 생각이 든다. 외우자.