1
1
class Solution :
2
2
def candy (self ,ratings :List [int ])-> int :
3
3
n = len (ratings )
4
- #Initialize with one candy becuase each child must have at least one candy.
4
+ # Initialize with one candy becuase each child must have at least one candy.
5
5
candies = [1 ]* n
6
6
7
- #Iterate from left to right
7
+ # Iterate from left to right
8
8
for i in range (1 ,n ):
9
- #Check if current rating is greater than left neighbor
10
- if ratings [i ]> ratings [i - 1 ]:
11
- #Rating is higher so deserves more candy than left neighbor
12
- candies [i ]= candies [i - 1 ]+ 1
9
+ # Check if current rating is greater than left neighbor
10
+ if ratings [i ]> ratings [i - 1 ]:
11
+ # Rating is higher so deserves more candy than left neighbor
12
+ candies [i ]= candies [i - 1 ]+ 1
13
13
14
- #Iterate from right to left
15
- for i in range (n - 2 ,- 1 ,- 1 ):
16
- #Check if current rating is greater than right neighbor
17
- if ratings [i ]> ratings [i + 1 ]:
18
- #Take max to check if the value is already greater than its right neighbor + 1.
19
- candies [i ]= max (candies [i ],candies [i + 1 ]+ 1 )
14
+ # Iterate from right to left
15
+ for i in range (n - 2 ,- 1 ,- 1 ):
16
+ # Check if current rating is greater than right neighbor
17
+ if ratings [i ]> ratings [i + 1 ]:
18
+ # Take max to check if the value is already greater than its right neighbor + 1.
19
+ candies [i ]= max (candies [i ],candies [i + 1 ]+ 1 )
20
20
21
- return sum (candies )
21
+ return sum (candies )