-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdistribute_candies.py
37 lines (28 loc) · 1.01 KB
/
distribute_candies.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
"""
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
1. Each child must have at least one candy.
2. Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Input Format: The first and the only argument contains N integers in an array A.
Output Format: Return an integer, representing the minimum candies to be given.
"""
def candy(r):
if len(r) <= 1:
return len(r)
c = [1] * len(r)
for i in range(1, len(r)):
if r[i] > r[i - 1]:
c[i] = c[i - 1] + 1
for i in range(len(r) - 1, 0, -1):
if r[i - 1] > r[i]:
c[i - 1] = max(c[i - 1], c[i] + 1)
return c
test_value1 = [1, 0, 2, 3, 5]
result1 = candy(test_value1)
print(result1) # [2, 1, 2, 3, 4]
print(sum(result1)) # 12
test_value2 = [1, 2, 2, 1, 4]
result2 = candy(test_value2)
print(result2) # [1, 2, 2, 1, 2]
print(sum(result2)) # 8