-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubarray_total_patch_containable.py
46 lines (36 loc) · 1.42 KB
/
subarray_total_patch_containable.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
#
# 42. Trapping Rain Water
# https://leetcode.com/problems/trapping-rain-water/
#
def totalPatch(heights: list[int]) -> int:
"""This can be related to 11. Container With Most Water
(subarray max area containable).
1) Greedy, Sliding Window
we moving two pointers from both ends, check the height against its bounded bar
at each index, and fill the value according to its bounded bar (containable)
we want to make sure that we wouldn't be in the situation that the opposite bounded
bar should be applied, so we are only going to update the bounded bar
when its value is smaller than the other side
|
| | |
| | | |
n,i,j,m
at each (i, j), we can fill the smaller value with the last updated bar
e.g. we will be filling j with (n-j) for the above, as n < m,
n would be last updated bar
time complexity: O(N), space complexity: O(1)
"""
i, j = 0, len(heights) - 1
fill, left_bar, right_bar = 0, 0, 0
while i < j:
if heights[i] > heights[j]:
# update the bounded bar when its value is smaller
# so that we are sure the bounded bar is shorter than the opposite
right_bar = max(right_bar, heights[j])
fill += right_bar - heights[j]
j -= 1
else:
left_bar = max(left_bar, heights[i])
fill += left_bar - heights[i]
i += 1
return fill