[LeetCode] 11. Container With Most Water

조현준조현준
2 min read

Link : https://leetcode.com/problems/container-with-most-water/description/

문제 정의

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the i<sup>th</sup> 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 <= 10<sup>5</sup>

  • 0 <= height[i] <= 10<sup>4</sup>

문제 분석

서로 다른 기둥이 있을 때 가장 많이 물을 담을 수 있는 범위를 구하는 문제입니다.

결국 서로 다른 기둥을 찾을 때에 최소 탐색으로 찾을 수 있도록 선택을 하는 것이 필요합니다.

이 문제는 직관적으로 ‘서로 다른 2개의 높이‘라는 부분에서 2 pointer 문제라는 것을 알 수 있기 때문에 그렇게 문제를 풀었습니다.

의사 코드는 다음과 같습니다

  1. left, right, answer 선언

  2. left < right 이면 반복

    1. height[left] < height[right]이면, left+1

    2. height[left] >= height[right]이면, right+1

의사 코드의 핵심은 높이가 낮은 쪽을 스킵하면서 진행된다는 것입니다.

왜냐하면 아무리 너비가 길어도 높이가 낮으면 최대 값이 되지 못하기 때문입니다.

해결 방안

import kotlin.math.min
import kotlin.math.max

class Solution {
    fun maxArea(height: IntArray): Int {
        var left = 0
        var right = height.lastIndex
        var maxArea = 0

        while (left < right) {
            val w = right - left
            val h = min(height[right], height[left])
            val area = w * h

            maxArea = max(maxArea, area)

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

        return maxArea
    }
}

느낀점

전형적인 2 pointer 문제이지만 아무 간단한 높이가 낮은 쪽부터 스킵한다는 생각을 못해서 시간을 많이 사용한 문제였던 것 같습니다.

0
Subscribe to my newsletter

Read articles from 조현준 directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

조현준
조현준