File tree Expand file tree Collapse file tree 2 files changed +47
-0
lines changed Expand file tree Collapse file tree 2 files changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution (object ):
2
+ def candy (self , ratings ):
3
+ N = len (ratings )
4
+
5
+ l2r = [1 ]* N
6
+ r2l = [1 ]* N
7
+
8
+ for i in xrange (1 , N ):
9
+ if ratings [i ]> ratings [i - 1 ]:
10
+ l2r [i ] = l2r [i - 1 ]+ 1
11
+
12
+ for i in xrange (N - 2 , - 1 , - 1 ):
13
+ if ratings [i ]> ratings [i + 1 ]:
14
+ r2l [i ] = r2l [i + 1 ]+ 1
15
+
16
+ ans = 0
17
+ for i in xrange (N ):
18
+ ans += max (l2r [i ], r2l [i ])
19
+
20
+ return ans
21
+
Original file line number Diff line number Diff line change
1
+ """
2
+ Let's calculate the answer considering only the left boandary.
3
+ The water each i can contain is wall[i-1]-height[i]
4
+ if no water at i-1 the wall[i-1] will be height[i-1], else it should be height[i-1]+water[i-1]
5
+ => water[i] = (height[i-1] + water[i-1]) - height[i] (l2r below)
6
+
7
+ Do the same from right to left, this time considering only the right boandary.
8
+
9
+ The amount of water at i considering both left and right wall will be min(l2r[i], r2l[i])
10
+ """
11
+ class Solution (object ):
12
+ def trap (self , height ):
13
+ N = len (height )
14
+ l2r = [0 ]* N #water
15
+ r2l = [0 ]* N #water
16
+
17
+ for i in xrange (1 , N ):
18
+ l2r [i ] = max (l2r [i - 1 ]+ height [i - 1 ]- height [i ], 0 )
19
+
20
+ for i in xrange (N - 2 , - 1 , - 1 ):
21
+ r2l [i ] = max (r2l [i + 1 ]+ height [i + 1 ]- height [i ], 0 )
22
+
23
+ ans = 0
24
+ for i in xrange (N ):
25
+ ans += min (l2r [i ], r2l [i ])
26
+ return ans
You can’t perform that action at this time.
0 commit comments