首页 > 代码库 > Candy
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?
答案
public class Solution { public int candy(int[] ratings) { if(ratings==null||ratings.length==0) { return 0; } int N=ratings.length; if(N==1) { return 1; } int []numCandy=new int[N]; int []bottom=new int[N]; int bottomIndex=-1; for(int i=0;i<N;i++) { numCandy[i]=-1; if(i==0){ if(ratings[0]<=ratings[1]) { bottom[++bottomIndex]=i; numCandy[i]=1; } } else { if(i==N-1) { if(ratings[i]<=ratings[i-1]) { bottom[++bottomIndex]=i; numCandy[i]=1; } } else { if(ratings[i]<=ratings[i-1]&&ratings[i]<=ratings[i+1]) { bottom[++bottomIndex]=i; numCandy[i]=1; } } } } int start=-1; int end=-1; for(int index=0;index<=bottomIndex;index++) { start=end; end=bottom[index]; int p=end-1; while(p>start&&numCandy[p]==-1) { numCandy[p]=numCandy[p+1]+1; p--; } if(p>0&&ratings[p]>ratings[p+1]) { numCandy[p]=Math.max(numCandy[p],numCandy[p+1]+1); } p=end+1; while(p<N&&numCandy[p]==-1) { numCandy[p]=numCandy[p-1]+1; if(p<N-1&&ratings[p]>=ratings[p+1]) { break; } p++; } } int result=0; for(int i=0;i<N;i++) { result+=numCandy[i]; } return result; } }
Candy
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。