Skip to content

Commit 28f997a

Browse files
author
Chris Wu
committed
no message
1 parent de66880 commit 28f997a

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

problems/candy.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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+

problems/trapping-rain-water.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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

0 commit comments

Comments
 (0)