Problem:
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Have you met this question in a real interview? Yes
Example
Given ratings = [1, 2], return 3.
given ratings = [1, 1, 1], return 3.
Given ratings = [1, 2, 2], return 4. ([1,2,1]).
Solution:
Initialize the candy array to 1s.
First go through from left to right;
Second go through form right to left with the following condition:
- If the current child’s rating is greater than the previous one, the current candies should be at least 1 more than the previous one
1 | /************************************************************************* |