-
-
Save Ex10si0n/2db075be24bd9e7c8b0e4ec91371021c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def trap(self, height: List[int]) -> int: | |
stack = [] | |
ans = 0 | |
for i in range(len(height)): | |
if not stack or height[i] < height[stack[-1]]: | |
stack.append(i) | |
else: | |
while stack and height[i] > height[stack[-1]]: | |
cur = stack.pop() | |
if not stack: | |
break | |
h = min(height[i], height[stack[-1]]) - height[cur] | |
w = i - stack[-1] - 1 | |
ans += h * w | |
stack.append(i) | |
return ans |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment