Candy
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⁴
- 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
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more greedy problems
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.