Candy
Some children stand in a row, and ratings[i] is the rating of child i. You hand out candies under two rules:
- every child gets at least one candy;
- a child whose rating is higher than an immediate neighbour's gets more candies than that neighbour.
Neighbours with equal ratings have no rule between them. Return the minimum total number of candies you need.
Constraints
1 <= ratings.length <= 2 * 10^40 <= ratings[i] <= 2 * 10^4
Examples
Example 1
Input: ratings = [1,3,2,2,1] Output: 7
Give 1, 2, 1, 2, 1 candies. The child rated 3 beats both neighbours, and the second child rated 2 beats the child rated 1 after it. Two children with equal ratings may get different amounts.
Example 2
Input: ratings = [2,2,2] Output: 3
Equal ratings never require more candy, so one candy each is enough.
Example 3
Input: ratings = [1,2,3,4] Output: 10
Every child is rated higher than the one before, so the amounts must climb: 1 + 2 + 3 + 4 = 10.
JavaScript you'll use: Arrays: create, read, update Numbers, Math and integer tricks
/**
* @param {number[]} ratings
* @return {number}
*/
function candy(ratings) {
}
Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.