Topic Description
There are N (n<=100000) children standing in a row (numbered from 0 to n-1), each child has a rating value, stored in the ratings array. Teachers need to assign candy to them, each child needs at least one candy, for any adjacent two children I and i+1,rating value must be smaller than the rating value of the distribution of sweets more (rating the same not necessary to allocate as much candy).
Please calculate the minimum number of sweets required to complete the above allocation.
Topic Online Practice Address: http://www.itint5.com/oj/#31
The first idea of this question is to sort the ratings and store the order in the sort array, but the time complexity is too high because of first sorting and then updating.
So give up the sort, but the positive sequence traversal, to see whether the adjacent number is reversed, and then go through the reverse sequence, to see if the adjacent number is reversed. This completes the assignment in the time Complexity of O (n).
public class Candy {
//returns the minimum number of sweets required public
long Minimalcandies (int[] ratings) {
int n = ratings.length;
if (n = = 0) {return
0;
}
Long sum = 0;
Int[] count = new Int[n];
for (int i = 0; i < n; i++) {
count[i] = 1;
}
for (int i = 0; i < n-1 i++) {
if (ratings[i]>ratings[i+1]) {
if (count[i]<=count[i+1)) {
Count[i] = count[i+1]+1;
}
} else if (ratings[i]<ratings[i+1]) {
if (count[i]>=count[i+1]) {
count[i+1] = count[i]+1;
}
}
} for
(int i = n-1 i > 0; i--) {
if (ratings[i]>ratings[i-1)) {
if (count[i]<=count[i-1)) {
count[i]= count[i-1]+1
}
} else if (Ratings[i]<ratings[i-1]) {
if (Count[i]>=count[i-1]) {
count[i-1]=count[i]+1
}
}} for
(int i = 0; i < n; i++) {
sum = sum+ count[i];
}
return sum;
}