Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions LeetCode/hard/trap_42.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from typing import List


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

left, right = 0, len(height) - 1
left_max, right_max = height[left], height[right]
res = 0

while left < right:
if left_max < right_max:
left += 1
left_max = max(left_max, height[left])
res += left_max - height[left]
else:
right -= 1
right_max = max(right_max, height[right])
res += right_max - height[right]

return res
23 changes: 23 additions & 0 deletions tests/test_leecode_hard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import pytest


@pytest.mark.parametrize(
"height, expected",
[
([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1], 6),
([4, 2, 0, 3, 2, 5], 9),
([], 0),
([1], 0),
([1, 2], 0),
([1, 2, 3, 4, 5], 0), # increasing
([5, 4, 3, 2, 1], 0), # decreasing
([3, 3, 3, 3], 0), # flat
([3, 0, 3], 3),
([5, 0, 5], 5),
([2, 0, 2], 2),
],
)
def test_trap(height, expected):
from LeetCode.hard.trap_42 import Solution

assert Solution().trap(height) == expected
Loading