Skip to content

Commit fccca5c

Browse files
committed
Candy
1 parent 765a293 commit fccca5c

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

135 Candy.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
'''
2+
There are N children standing in a line. Each child is assigned a rating value.
3+
4+
You are giving candies to these children subjected to the following requirements:
5+
6+
Each child must have at least one candy.
7+
Children with a higher rating get more candies than their neighbors.
8+
What is the minimum candies you must give?
9+
'''
10+
11+
class Solution(object):
12+
def candy(self, ratings):
13+
"""
14+
:type ratings: List[int]
15+
:rtype: int
16+
"""
17+
n = len(ratings)
18+
candy = [1] * n
19+
for i in range(1, n):
20+
if ratings[i] > ratings[i - 1]:
21+
candy[i] = candy[i - 1] + 1
22+
for i in range(n - 2, -1, -1):
23+
if ratings[i] > ratings[i + 1]:
24+
candy[i] = max(candy[i], candy[i + 1] + 1)
25+
return sum(candy)
26+
27+
28+
if __name__ == "__main__":
29+
assert Solution().candy([1, 2, 3, 7, 4, 3, 2, 1]) == 21

0 commit comments

Comments
 (0)