LeetCode Container With Most Water (JavaScript)

2025. 11. 16. 19:07·코딩테스트/LeetCode

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

문제 설명

더보기

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.

Example 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

Constraints:

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

문제 풀이

투 포인터 알고리즘을 이용하여 해결

left : 왼쪽 끝, right : 오른쪽 끝

left, right에 해당하는 높이중 낮은 높이를 기준으로 넓이를 구함 -> answer 최신화 (큰 값으로)

left, right 중 작은 값을 이동 시킴 (이동 시킴으로 써 더 큰 높이를 만나기 위해)

/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function(height) {
    let answer = 0;

    let [left, right] = [0, height.length - 1];

    while (left < right) {
        const h = Math.min(height[left], height[right]);
        const r = right - left;
        answer = Math.max(answer, h * r);

        if (height[left] < height[right]) {
            left++;
        } else {
            right--;
        }
    }

    return answer;
};

 


결론

투 포인터 알고리즘을 통해 구현

포인터를 이동시키는 로직이 핵심

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode 4Sum (JavaScript)  (0) 2025.11.17
LeetCode Letter Combinations of a Phone Number (JavaScript)  (0) 2025.11.17
LeetCode Zigzag Conversion (JavaScript)  (0) 2025.11.16
LeetCode Longest Palindromic Substring (JavaScript)  (0) 2025.11.16
LeetCode Add Two Numbers (JavaScript)  (0) 2025.11.16
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode 4Sum (JavaScript)
  • LeetCode Letter Combinations of a Phone Number (JavaScript)
  • LeetCode Zigzag Conversion (JavaScript)
  • LeetCode Longest Palindromic Substring (JavaScript)
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (212) N
      • 프론트엔드 (64) N
        • JavaScript (51)
        • HTML (3)
        • React (7) N
        • CSS (2)
        • CS (1)
      • 프로젝트 (19)
        • Portfolio 사이트 개발 (19)
      • 코딩테스트 (126) N
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (61)
        • LeetCode (37) N
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Container With Most Water (JavaScript)
상단으로

티스토리툴바