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

    就是个坑啊!

    首先,竟然允许相邻的2个人同样ranking!!!!他们还怎么做朋友!

    其次,对于ranking为 123333321的这组,你猜~~~

    class Solution {
    public:
        int candy(vector<int> &ratings) {
            int size = ratings.size();
            vector<int> num(size,1);
            vector<int> min;
            if(size == 1)return 1;
            if(size == 2)
            if(ratings[0]==ratings[1])return 2;
            else
            return 3;
    
            for(int i = 1 ; i < size-1 ;i++)
            {
                if(ratings[i-1]>=ratings[i] && ratings[i] <= ratings[i+1])min.push_back(i);
            }
            int i=0;
            while(i+1<size && ratings[i+1] >= ratings[i])
            {
                if(ratings[i+1] == ratings[i])
                //num[i+1] = 1;
                ;
                else
                num[i+1] = num[i]+1;
                i++;
            }
            i = size -1;
            while(i>=1 && ratings[i-1] >= ratings[i])
            {if(ratings[i-1] == ratings[i])
            //num[i-1] = 1;
            ;
            else 
            num[i-1] = num[i]+1; i--;}
            
            for(int j = 0 ; j < min.size(); j++)
            {
                int t = min[j];
                i=t;
                while(i >= 0 && ratings[i-1] >= ratings[i])
                {
                    if(num[i -1] <= num[i])
                    if(ratings[i-1] == ratings[i])
                    //num[i-1] = num[i]
                    ;
                    else
                    num[i-1] = num[i]+1;
                    
                    i--;
                }
                
                i=t;
                while(i <size && ratings[i+1] >= ratings[i])
                {
                    if(num[i +1] <= num[i])
                    if(ratings[i+1] == ratings[i])
                    //num[i+1] = num[i]
                    ;
                    else
                    num[i+1] = num[i] +1;
                    
                    i++;
                }
            }
            int re = 0;
            for( i = 0 ; i < size ;i++)
            re += num[i];
            return re;
        }
    };
    

      

  • 相关阅读:
    ubuntu 下python安装及hello world
    mongodb数据库学习【安装及简单增删改查】
    samba服务器共享开发【windows下开发linux网站】
    系统架构一:snmp+mrtg服务器监控
    记.gitignore的一次惊心动魄
    第一章 引论 第二章 算法分析
    渗透测试实践指南(1)
    day7
    day5 io模型
    day4(带)
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3627226.html
Copyright © 2011-2022 走看看