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?
public class Solution { public int candy(int[] ratings) { /*其实只要左右不比他大,就可以只分1个。如果左右比他大,左右就多分一个。这样的结果就是最省的。 其实题目的描述本身就是一个很好的方案:初始化将每个人的糖果数都初始化为1。每次遍历只考虑左右一边, 即从左向右遍历,如果i>i-1 则 candy[i]=candy[i-1]+1;再从右向左遍历一次,如果i>i+1 并且 candy[i]<=candy[i+1](注意!!) 则 cand[i]=candy[i+1]+1; 这样的两次遍历,左右两边都顾及到了。最后将candy[i]相加求和就好了。 每一边只考虑递增序列!!!*/ if(ratings==null||ratings.length<1) return 0; int len=ratings.length; int candy[]=new int[len]; int res=0; for(int i=0;i<len;i++){ candy[i]=1; } for(int i=1;i<len;i++){ if(ratings[i-1]<ratings[i]){ candy[i]=candy[i-1]+1; } } for(int i=len-2;i>=0;i--){ if(ratings[i+1]<ratings[i]&&candy[i]<=candy[i+1]){//// candy[i]=candy[i+1]+1; } } for(int i=0;i<len;i++){ res+=candy[i]; } return res; } }
时间: 2024-10-07 18:20:34