본문 바로가기
LeetCode/Two Pointers

[LeetCode][Kotlin] 42. Trapping Rain Water

by jinwo_o 2024. 10. 21.

42. Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

너비가 1인 고도 지도를 나타내는 음이 아닌 정수 n개가 주어졌을 때, 비가 내린 후에 얼마나 많은 물을 가둘 수 있는지 계산하세요.

 

Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]

Output: 6

Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

 

Example 2:

Input: height = [4,2,0,3,2,5]

Output: 9

 

Constraints:

  • n == height.length
  • 1 <= n <= 2 * 10^4
  • 0 <= height[i] <= 10^5

코드

class Solution {
    fun trap(height: IntArray): Int {
        var l = 0
        var r = height.lastIndex

        var leftMax = height[l]
        var rightMax = height[r]
        var answer = 0

        while (l < r) {
            if (leftMax < rightMax) {
                l++
                leftMax = maxOf(leftMax, height[l])
                answer += leftMax - height[l]
            } else {
                r--
                rightMax = maxOf(rightMax, height[r])
                answer += rightMax - height[r]
            }
        }

        return answer
    }
}