-
Notifications
You must be signed in to change notification settings - Fork 2
/
TrappingRainWater.py
77 lines (69 loc) · 2.73 KB
/
TrappingRainWater.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from typing import List
# Hint: Calculate the gap between each bar and the highest bar.
class Solution1:
def trap(self, height: List[int]) -> int:
if len(height) < 3:
return 0
max_height = max(height)
gap_to_max_height = []
water_trap = 0
for h in height:
gap_to_max_height.append(max_height - h)
current = 0
forward = current + 1
while forward < len(gap_to_max_height):
if gap_to_max_height[current] == 0 or gap_to_max_height[forward] == 0:
# When encounter the highest bar, break the loop and going backward
break
if gap_to_max_height[current] >= gap_to_max_height[forward]:
current = forward
forward = current + 1
else:
water_trap += (gap_to_max_height[forward] - gap_to_max_height[current])
forward += 1
current = len(gap_to_max_height) - 1
backward = current - 1
while backward >= forward:
if gap_to_max_height[current] >= gap_to_max_height[backward]:
current = backward
backward = current - 1
else:
water_trap += (gap_to_max_height[backward] - gap_to_max_height[current])
backward -= 1
return water_trap
class Solution2:
def trap(self, height: List[int]) -> int:
if len(height) < 3:
return 0
max_height = max(height)
gap_to_max_height = []
water_trap = 0
for h in height:
gap_to_max_height.append(max_height - h)
current = 0
forward = current + 1
change_backward = False
while forward < len(gap_to_max_height):
if gap_to_max_height[current] == 0 or gap_to_max_height[forward] == 0:
current = forward
forward = current + 1
change_backward = True
if not change_backward:
if gap_to_max_height[current] >= gap_to_max_height[forward]:
current = forward
forward = current + 1
else:
water_trap += (gap_to_max_height[forward] - gap_to_max_height[current])
forward += 1
else:
if gap_to_max_height[current] < gap_to_max_height[forward]:
current = forward
forward = current + 1
else:
water_trap += (gap_to_max_height[current] - gap_to_max_height[forward])
forward += 1
return water_trap
print(Solution1().trap([0,1,0,2,1,0,1,3,2,1,2,1]))
# expected: 6
print(Solution2().trap([4, 2, 3]))
# expected: 1