Candy at summer camp
- O(n²) · Very hard
- Full plan
- Python
- JavaScript
- lists
- loops
- comparisons
Problem
Marisol hands out candy at the end of the camp day. The kids are already in line, each with a score, and she wants to spend as little as she can without anyone complaining.
You get the list of scores in line order (whole numbers; it may be empty). Every kid gets at least one candy, and a kid with a higher score than a neighbor right next to them, on the left or on the right, gets more candy than that neighbor. Equal scores carry no rule: either of the two may get less. Return the smallest possible total of candy, as a whole number. With no kids, it is 0.
With [3, 1, 2, 2]: the 1 gets 1; the 3 and the first 2 beat the 1 and get 2 each; the last 2 ties with its neighbor, so 1 is enough.
You return 6.
Examples
The example
[3, 1, 2, 2] → 6
The middle one is the lowest
[1, 0, 2] → 5
The line goes from high to low
[5, 4, 3, 2, 1] → 15
The line goes from low to high
[1, 2, 3, 4] → 10
Up and then down
[1, 3, 5, 4, 2, 1] → 13
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def total_candy(scores):
passJavaScript
function totalCandy(scores) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.