首页 > 其他 > 详细

candy(动态规划)

时间:2017-11-12 16:02:25      阅读:221      评论:0      收藏:0      [点我收藏+]

题目描述


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?

题意:n 个小孩,每个小孩有一个评分。给小孩发糖。要求:

    1)每个小孩至少一颗糖

    2)评分高的小孩发的糖比他旁边两个小孩的多

因此最少需要多少糖果才够分?

 

解题思路:

  遍历两边,首先每个人得一块糖,第一遍从左到右,若当前点比前一个点高就比前者多一块。

这样保证了在一个方向上满足了要求。第二遍从右往左,若左右两点,左侧高于右侧,但

左侧的糖果数不多于右侧,则左侧糖果数等于右侧糖果数+1,这就保证了另一个方向上满足要求。

  最后将各个位置的糖果数累加起来就可以了。

代码实现:

class Solution {
public:
    int candy(vector<int> &ratings) {
        int n=ratings.size();
        //candy set
        vector<int>Candy(n,1);
        //from left to right
        for(int i(0);i<n-1;i++){
            if(ratings[i+1]>ratings[i])
                Candy[i+1]=Candy[i]+1;
        }
        //from right to left
        for(int j=n-1;j>0;j--){
            if(ratings[j-1]>ratings[j]&&Candy[j-1]<=Candy[j])
                Candy[j-1]=Candy[j]+1;
        }
        //add all
        int sum(0);
        for(auto a:Candy)
            sum+=a;
        return sum;
    }
};

 

candy(动态规划)

原文:http://www.cnblogs.com/ktao/p/7821803.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!