leetCode练习(135)

题目:candy

难度:HARD

问题描述:

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?

Example 1:

Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
             The third child gets 1 candy because it satisfies the above two conditions.

结题思路:

扫描二维码关注公众号,回复: 1484511 查看本文章

 * 从左往右顺一遍,r[i]>r[i-1],则 per[i]=per[i-1]+1,否则 per[i]=1;
 * 再从右往左顺一遍,r[i-1]>r[i],则per[i-1] = max(per[i]+1,per[i-1])

代码如下:

public int candy(int[] ratings) {
        int size = ratings.length;
        if(size<2) return size;
        int[] per = new int[size];	//每人至少0根,最后加上size即可
        for(int i=1;i<size;i++){
        	if(ratings[i]>ratings[i-1]){
        		per[i] = per[i-1]+1;
        	}
        }
        for(int i=size-1;i>0;i--){
        	if(ratings[i-1]>ratings[i]){
        		per[i-1] = Math.max(per[i-1], per[i]+1);
        	}
        }
        int res = size;
        for(int w : per){
        	res += w;
        }
        return res;
    }


猜你喜欢

转载自blog.csdn.net/u010771890/article/details/80586865