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

贪心算法:

贪心算法分阶段工作,在每个阶段,可以认为所做的决定是最好的,而不考虑将来的后果。意味着选择的是局部最优化。

这种“眼下能拿到的就拿”的策略即是这类算法名字的来源。当算法终止时,将得到全局最优。

复制代码
class Solution {
public:
    int candy(vector<int> &ratings) {
        vector<int>::size_type number = ratings.size(); 
        vector<int> candies(number,1);
        int sum = 0;
        for(vector<int>::size_type st=0;st<number-1;st++)//从前往后依次比较相邻两位
        {
           if(ratings[st+1]>ratings[st])
               candies[st+1] = candies[st]+1;
        }
        for(vector<int>::size_type stRev=number-1;stRev>0;stRev--)//从后往前依次比较相邻两位
        {
           if(ratings[stRev]<ratings[stRev-1] && candies[stRev-1]<=candies[stRev])//注意此处条件比上一个从前往后的条件更严谨,如果和上面条件一样贪心算法还是局部最优
               candies[stRev-1]=candies[stRev]+1;
        }
        for(vector<int>::size_type st=0;st<number;st++)
            sum += candies[st];
        return sum;
    }
};
复制代码

另外参考Felix的博客, http://www.cnblogs.com/felixfang/p/3620086.html,第二种算法,不需要上面贪心算法的O(n)时间。

posted @   Xylophone  Views(172)  Comments(0Edit  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示