码迷,mamicode.com
首页 > 其他好文 > 详细

Candy

时间:2014-09-20 10:05:17      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:style   color   io   java   ar   for   div   art   sp   

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

标签:style   color   io   java   ar   for   div   art   sp   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39429289

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!