Candy

Hard#135two passes

Children stand in a row, each with a rating. Give them candies: everyone gets at least one, and a child rated higher than a neighbour gets more than that neighbour. Find the fewest candies in all. Our example: [2, 4, 3, 5, 2, 1, 1, 3] — the answer is 13: [1, 2, 1, 3, 2, 1, 1, 2].

input
ratings: the ratings of children standing in a row.
returns
The fewest candies to hand out so that every child gets at least one, and a child rated higher than a neighbour gets more than that neighbour.
constraints
  • 1 ≤ ratings.length ≤ 5000
  • 0 ≤ ratings[i] ≤ 2·10⁴
our 14 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} ratings
 * @return {number}
 */
function candy(ratings) {

}
Ctrl ↵
format
reset

saved in this browser

14 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more greedy problems

Pattern “Greedy” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.