본문 바로가기
LeetCode/Problems

LeetCode 42. Trapping Rain Water [Hard]

by 벤진[Benzene] 2020. 8. 24.

Problem:

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


The above elevation map 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. Thanks Marcos for contributing this image!

 

Example:

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

Output: 6

 

Summary:

#Using Two-pointer.

 

While the left pointer is smaller than right pointer, we keep moving each left and right pointer.

Setup initial left and right max height and keep update while we move on. Compare the difference height between current height and max left / right height, then add the volume of the difference.

It will stop in the maximum height of the height list and return with a total volume from left and right.

 

Code:

class Solution:
    def trap(self, height: List[int]) -> int:
        if not height:
            return 0
        
        volume = 0
        
        left, right = 0, len(height)-1
        
        max_left, max_right = height[left], height[right]
        
        while left < right:
            max_left, max_right = max(max_left, height[left]), max(max_right, height[right])
            
            if height[left] <= height[right]:
                volume += max_left - height[left]
                left += 1
            else:
                volume += max_right - height[right]
                right -= 1
        
        return volume

Runtime:

O(n)

 

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

'LeetCode > Problems' 카테고리의 다른 글

LeetCode 561. Array Partition I [Easy]  (0) 2020.08.26
LeetCode 15. 3Sum [Medium]  (0) 2020.08.25
LeetCode 49. Group Anagrams  (0) 2020.08.19
LeetCode 819. Most Common Word  (0) 2020.08.18
LeetCode 937. Reorder Data in Log Files  (0) 2020.08.17

댓글