CS/PS

[PS] Leet | 11. 가장 큰 컨테이너

Rayi 2025. 3. 24. 12:59

문제

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

예시

Exampe 1

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example 2:
Input: height = [1,1]
Output: 1

조건

  • n == height.length
  • 2 <= n <= 105
  • 0 <= height[i] <= 104

양 끝을 시작으로 범위를 좁혀가면서 각 경우에 대해 최댓값을 비교하는 two-pointer 알고리즘을 사용합니다.

 

왼쪽 벽이 오른쪽 벽보다 낮을 때는 오른쪽 벽의 높이와 관계 없이 최소 높이가 결정되므로, 왼쪽 벽만 이동합니다.

 

반대의 경우에는 같은 이유로 오른쪽 벽만 이동합니다.

/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function(height) {
    let maxAreaValue = 0;
    let left = 0;
    let right = height.length - 1;

    while (left < right) {
        let area = 0;
        
        if (height[left] < height[right]){
            area = height[left] * (right - left);
            left++;
        } else {
            area = height[right] * (right - left);
            right--;
        }
        maxAreaValue = Math.max(maxAreaValue, area);
    }
    return maxAreaValue;
};

 

시간 복잡도 : O(n)

공간 복잡도 : O(1)

728x90