InferenceAI

Enter at least two characters to search.

Start free

Fair Candy

hardGreedy & Intervals40 min50 XP

Children stand in a line with ratings. Each gets at least one candy, and a child with a higher rating than a neighbour must get more candy than that neighbour. Return the minimum total candy.

Examples

EXAMPLE WALKTHROUGHvalley

A guided view of the published example, not a trace of your code.

INPUT[[1,0,2]]
TASKfair_candy()
EXPECTED OUTPUT5

Start with the input values shown in this example.

Example 1 of 3

Input: ratings = [1,0,2]

Output: 5

Explanation: valley

Input: ratings = [1,2,2]

Output: 4

Explanation: equal ratings

Input: ratings = [1]

Output: 1

Explanation: single

Hint 1

One pass left to right handles left neighbours; one pass right to left handles right neighbours.

Hint 2

Take the maximum of the two requirements for each child.

Topics

DSAGreedy & IntervalsPython