Skip to content
BytePatterns

Fair Candy Shares

HardGreedy#greedy#two-pass~40m

Problem

Children stand in a row and each has a score. Every child must get at least one sweet, and a child whose score is higher than a direct neighbour's must get more sweets than that neighbour. Equal scores place no demand either way. Return the smallest total number of sweets that meets both rules.

Examples

Input:  scores = [1, 0, 2]
Output: 5
Why:    hand out 2, 1, 2
Input:  scores = [1, 2, 2]
Output: 4
Why:    hand out 1, 2, 1; the last child only has to beat nobody
Input:  scores = [7]
Output: 1
Why:    edge case, a lone child still needs one sweet

Hints

0 / 3

Stuck on the idea rather than the code? What Makes Greedy Work covers it.