zoukankan      html  css  js  c++  java
  • [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;
        }
    };
    

      

  • 相关阅读:
    如何使用Java计算货币/钱~(How to calculate monetary values in Java)
    BigDecimal类
    状态码定义
    常见服务器返回状态码(Status Codes)
    2020-3-26学习地图
    ReentrantLock类
    HashSet类
    Vector类
    课程总结
    第十四周课程总结&实验报告
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3427811.html
Copyright © 2011-2022 走看看