Skip to content

Instantly share code, notes, and snippets.

@Ex10si0n

Ex10si0n/trap.py Secret

Created June 13, 2024 20:48
Show Gist options
  • Save Ex10si0n/2db075be24bd9e7c8b0e4ec91371021c to your computer and use it in GitHub Desktop.
Save Ex10si0n/2db075be24bd9e7c8b0e4ec91371021c to your computer and use it in GitHub Desktop.
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