Topic
There are N children standing in a line. Each child is assigned a rating value.
You are are giving candies to this children subjected to the following Requirements:each child must have at least one one candy. Children with a higher rating to more candies than their.
What is the minimum candies for you must give?
Meaning
A number of children stand in a row, according to their score distribution candy, scored high children than next to lower scores of children get more candy, each child at least get a candy, ask at least how many sweets to prepare.
Ideas
First scan from left to right, so that the right side than the left to score higher than the left of the number of sweets more candy.
Again from the right to the left scan again, so that the left side than the right to score higher than the number of sweets more than the right.
"Java Code"
public class Solution {public
int candy (int[] ratings) {
int size = ratings.length;
if (size = = 0) return-1;
if (size = = 1) return 1;
Int[] cans = new Int[size];
Cans[0] = 1;
Forward scan, if the right side of the rating higher than the left, then the right candy number is more than the left one, otherwise only give a candy for
(int i = 1; i < size; i++) {
if (ratings[i) > ratings[ I-1]) cans[i] = cans[i-1] + 1;
else cans[i] = 1;
}
Reverse scan again, if the left side of the rating is higher than the right, and the number of sweets on the left is less than the right, then the left candy number should be more than the right one for
(int i = size-2; I >= 0; i--) {
if (ratings[i) ; Ratings[i + 1] && cans[i] <= cans[i + 1]) {
Cans[i] = cans[i + 1] + 1;
}
int ret = 0;
for (int i = 0; i < size; i++) {
ret + cans[i];
}
return ret;
}
}
This algorithm is really to think out, and later found that the Internet is also such a solution, indeed feel very happy.
Although the idea is right, but submitted three or four times to AC. The first is to forget the judgment (size = = 1), which is actually not written (Ratings[i] > ratings[i + 1] && cans[i] <= cans[i + 1]), because if the left candy number itself Already more than the right, then changed to cans[i] = cans[i + 1] + 1; It is possible to make cans[i] smaller.