Greedy Algorithms8 sections · 316 units
Open in Course

Candy - Implementation

The code

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: O(n)O(n). Space: O(n)O(n).