1 topics
There is N children standing in a line. Each child is assigned a rating value.
You is giving candies to these children subjected to the following requirements:
- Each child must has at least one candy.
- Children with a higher rating get more candies than their neighbors.
What's the minimum candies you must give?
2 Ideas
According to the line of thought, each child has at least one candy, first from left to right to go through, write up the number of increased candy, and then walk from right to left to complete the decreasing number of sweets. This approach can be used for problems related to the size and left and right side data. In addition, there is another space complexity O (1), Time complexity O (n) ideas, can refer to http://www.cnblogs.com/felixfang/p/3620086.html.
3 Code
Public intCandyint[] ratings) { if(Ratings = =NULL|| Ratings.length = = 0) { return0; } int[] Candynums =New int[Ratings.length]; candynums[0] = 1; for(inti = 1; i < ratings.length; i++) { if(Ratings[i] > Ratings[i-1])//If the first child is taller than the I-1 child, {candynums[i]= Candynums[i-1]+1; } else//Everyone has at least one candy{Candynums[i]= 1; } } for(inti = ratings.length-2; I >= 0; i--) { if(Ratings[i] > ratings[i + 1] && candynums[i] <= candynums[i + 1])//If the first child is taller than the i + 1 child and the candy is less than i+1 sweets {candynums[i]= Candynums[i + 1] + 1; } } intTotal = 0; for(inti = 0; i < candynums.length; i++) { Total+=Candynums[i]; } returnTotal ; }
[Leet Code 135]candy