loading

Candy — Step-by-Step Visualization

hardLeetCode #135ArrayGreedy

There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings. Give the minimum number of candies such that: each child has at least 1 candy, and children with a higher rating than their neighbor get more candies.

Algorithm Pattern

Two-Pass Greedy

Key Idea

First pass satisfies left neighbors, second pass satisfies right neighbors.

Step-by-Step Approach

  1. Init all candies to 1
  2. Left→right: if rating[i] > rating[i-1], increment candy[i]
  3. Right→left: if rating[i] > rating[i+1] and candy[i] <= candy[i+1], set candy[i] = candy[i+1]+1
  4. Sum all candies

Related Problems