Fork me on GitHub

[leetcode-135-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?

思路很朴素:两次遍历,从前往后和从后往前遍历。

 

int candy(vector<int>& ratings)
    {
        if (ratings.size() == 0) return 0;
    //    sort(ratings.begin(), ratings.end());
        int sum = 0;//第一个为1
        vector<int>candyvec(ratings.size(),1);
        for (int i = 1; i < ratings.size();i++)
        {
            if (ratings[i] > ratings[i-1])//如果相等
            {
                candyvec[i] = candyvec[i - 1]+1;
            }
            else
            {
                candyvec[i] = 1;//最少1个
            }
        }
        sum = candyvec[ratings.size() - 1];
        for (int i = ratings.size() - 2; i >=0 ;i--)//反向遍历一遍 
        {
            if ((ratings[i] > ratings[i + 1]) && candyvec[i] < (candyvec[i + 1] + 1))candyvec[i] = candyvec[i + 1] + 1;
            sum += candyvec[i];
        }
         
        return sum;
    }

 

参考:

https://leetcode.com/problems/candy/?tab=Solutions

posted @ 2017-02-28 17:25  hellowOOOrld  阅读(192)  评论(0编辑  收藏  举报