AAlgoLoopSpaced repetition for LeetCode
HARDGreedyLeetCode ↗

Candy

The key idea

A higher rating than a neighbor must mean strictly more candies. Each child is constrained from two independent sides: its left neighbor and its right neighbor. Handle the two directions in two separate greedy passes, then take the larger requirement at each position so both constraints hold at once.

Problem

There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.

You are giving candies to these children subjected to the following requirements:

- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.

Return the minimum number of candies you need to have to distribute the candies to the children.

Constraints

Examples

Input: ratings = [1,0,2] Output: 5
Input: ratings = [1,2,2] Output: 4

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Greedy problems