Problem 248
Candy Distribution
Problem
N children stand in a line, and child i has a rating R[i]. You hand out candies under two rules: every child gets at least one candy, and a child with a higher rating than a neighbour must get more candies than that neighbour. Children with equal ratings have no requirement between them. Find the minimum total number of candies. Two passes do it. From left to right, give each child one more candy than the left neighbour if their rating is higher, otherwise 1. From right to left, raise each child to one more than the right neighbour if their rating is higher. The total of the final amounts is the answer.
Input
First line: N. Second line: N ratings.
Output
Print the minimum number of candies.
Constraints
1 <= N <= 100000; 0 <= R[i] <= 20000
Example input
3 1 0 2
Example output
5
Explanation
With ratings 1 0 2, the middle child has the lowest rating and gets 1 candy. Both other children rate higher than the middle one, so each needs 2. The total is 2 + 1 + 2 = 5.