function candy(ratings)
n := length of ratings
candies := array of size n, all initialized to 1
// Left to right
for i from 1 to n - 1
if ratings[i] > ratings[i-1] then
candies[i] := candies[i-1] + 1
// Right to left
for i from n - 2 down to 0
if ratings[i] > ratings[i+1] then
candies[i] := max(candies[i], candies[i+1] + 1)
return sum of candies
Time: . Space: .