codejump
MediumPro challengePythonJavaScriptTypeScript

Greedy — Candy

AlgorithmsGreedyArrays

solve(ratings) — children stand in a line, each with a rating. Give every child at
least one candy, and give a child **more candies than a neighbour with a lower
rating (on either side). Return the minimum total number of candies**.

Make two passes: left to right so each child with a higher rating than the left
neighbour has more candies, then right to left for the right neighbour, keeping the
larger requirement.

Examples

solve([1,0,2])      → 5     // 2, 1, 2
solve([1,2,2])      → 4     // 1, 2, 1
solve([1,2,3,4])   → 10
solve([1,3,2,2,1])  → 7     // 1, 2, 1, 2, 1

Sample tests

Test #1Classic example
Input: [[1,0,2]]
Output: 5
Test #2Equal neighbours
Input: [[1,2,2]]
Output: 4
Test #3One child
Input: [[1]]
Output: 1