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

2025. 3. 24. 12:59·CS/PS

문제

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

'CS > PS' 카테고리의 다른 글

[PS] Leet | 300. 가장 긴 증가 수열  (0) 2025.04.02
[PS] Leet | 322. 동전 교환  (0) 2025.03.28
[PS] 같은 수의 뉴런  (0) 2025.03.21
[PS] Leet | 15. 세 개의 합  (0) 2025.03.21
[PS] 가장 가까운 두 수  (0) 2025.03.21
'CS/PS' 카테고리의 다른 글
  • [PS] Leet | 300. 가장 긴 증가 수열
  • [PS] Leet | 322. 동전 교환
  • [PS] 같은 수의 뉴런
  • [PS] Leet | 15. 세 개의 합
Rayi
Rayi
  • Rayi
    아카이브
    Rayi
  • 전체
    오늘
    어제
    • 분류 전체보기 (262)
      • CS (40)
        • ML (3)
        • CV (2)
        • PS (34)
      • Reveiw (17)
        • Paper (17)
        • Github (0)
      • Pytorch (5)
      • Language (58)
        • Python (7)
        • JavaScript (32)
        • TypeScript (16)
        • C++ (3)
      • IDE (12)
      • Git (13)
      • Frontend (71)
        • React (8)
        • SolidJS (20)
        • CSS (12)
      • UI (3)
      • Backend (15)
        • DB (17)
        • Node.js (11)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    CS
    Git
    review
    CV
    PRISMA
    ML
    postgresql
    vscode
    mongo
    GAN
    deploy
    js
    ts
    react
    html
    PyTorch
    Three
    ps
    API
    nodejs
    SOLID
    python
    backend
    UI
    Express
    figma
    C++
    DB
    frontend
    CSS
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Rayi
[PS] Leet | 11. 가장 큰 컨테이너
상단으로

티스토리툴바