• [LeetCode]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?

    思考:提交了好多次,终于弄明白题意。有一点是需要注意的,当相邻两个小孩的等级值相同时,他们的糖果数可以不同。

            遍历两次。第一次从左往右,确定右邻居合法,即当等级值变大时,小孩糖果数加1,否则为1。第二次遍历从右往左,确定左邻居合法,即当等级值变大时并且原先遍历不合法时,小孩糖果数加1,否则不变。

    class Solution {
    public:
        int candy(vector<int> &ratings) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            int ret=0;
    		int len=ratings.size();
    		int *p=new int[len];
    		memset(p,0,sizeof(int)*len);
    		int i;
    		p[0]=1;
    		for(i=1;i<len;i++)
    		{
    			if(ratings[i]>ratings[i-1])
    				p[i]=p[i-1]+1;
    			else
    				p[i]=1;
    		}
    		for(i=len-2;i>=0;i--)
    		{
    			if(ratings[i]>ratings[i+1]&&(p[i]<=p[i+1]))
    				p[i]=p[i+1]+1;
    		}
    		for(i=0;i<len;i++)
    		{
    			ret+=p[i];
    		}
    		delete []p;
    		return ret;
        }
    };
    

      

  • 相关阅读:
    友盟消息推送api、python sdk问题、测试demo代码
    Django的时区设置问题
    优酷视频上传api及demo代码
    git回滚线上代码
    charles的使用
    django+ajax用FileResponse文件下载到浏览器过程中遇到的问题
    scrapy框架
    几个简单的算法
    SQLAlchemy
    redis
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3427811.html
Copyright © 2020-2023  润新知