Leetcode 42. Trapping Rain Water

이재윤·2024년 12월 2일
0

https://leetcode.com/problems/trapping-rain-water/

  1. 코드
class Solution:
    def trap(self, height: List[int]) -> int:
        
        if not height: return 0

        l, r = 0, len(height)-1
        leftMax, rightMax = height[l], height[r]
        res = 0

        while l < r:
            if leftMax < rightMax:
                l += 1
                leftMax = max(leftMax, height[l])
                res += leftMax - height[l]
            else:
                r -= 1
                rightMax = max(rightMax, height[r])
                res += rightMax - height[r]

        
        return res
  1. 설명
  • 투 포인터로 접근하는 문제입니다.
    배열의 맨 왼쪽과 맨 오른쪽에 값을 각각 하나씩(leftMax, rightMax) 설정하고,
    두 값을 비교해서 작은 값을 한 칸씩 순차적으로 이동시킵니다.
  • 그리고 해당 이동한 위치에서 고여 있는 빗물을 계산해서 더해주는
    방식으로 접근합니다.

0개의 댓글