Candy
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?
思想:确定变量分析法,先确定一个变量,然后进行分析. 先确保一侧满足条件,然后来调整另外一侧。
java代码:
- public int candy(int[] ratings) {
- int rlen = ratings.length;
- if(rlen==0) return 0;
- if(rlen==1) return 1;
- int[] candy = new int[rlen];
- for(int i=0;i<rlen;i++) {
- candy[i] = 1;
- }
- for(int i=1;i<rlen;i++) {
- if(ratings[i] > ratings[i-1]) {
- candy[i] = candy[i-1] + 1;
- }
- }
- for(int j=rlen-2;j>=0;j--) {
- if(ratings[j] > ratings[j+1]) {
- candy[j] = Math.max(candy[j],candy[j+1]+1);
- }
- }
- int sum = 0;
- for(int i=0;i<rlen;i++) {
- sum+=candy[i];
- }
- return sum;
- }

浙公网安备 33010602011771号