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?

 

参考:http://www.cnblogs.com/TenosDoIt/p/3389479.html

初始化所有小孩糖数目为1,从前往后扫描,如果第i个小孩等级比第i-1个高,那么i的糖数目等于i-1的糖数目+1;从后往前扫描,如果第i个的小孩的等级比i+1个小孩高,但是糖的数目却小或者相等,那么i的糖数目等于i+1的糖数目+1。

这道题用到的思路和Trapping Rain Water是一样的,用动态规划。基本思路就是进行两次扫描,一次从左往右,一次从右往左。第一次扫描的时候维护对于每一个小孩左边所需要最少的糖果数量,存入数组对应元素中,第二次扫描的时候维护右边所需的最少糖果数,并且比较将左边和右边大的糖果数量存入结果数组对应元素中。这样两遍扫描之后就可以得到每一个所需要的最最少糖果量,从而累加得出结果。方法只需要两次扫描,所以时间复杂度是O(2*n)=O(n)。空间上需要一个长度为n的数组,复杂度是O(n)。

C++代码如下: 

#include<iostream>

#include<vector>

using namespace std;



class Solution

{

public:

    int candy(vector<int> &ratings)

    {

        if(ratings.empty())

            return 0;

        int n=ratings.size();

        int num[n];

        num[0]=1;

        int i;

        for(i=1; i<n; i++)

        {

            if(ratings[i]>ratings[i-1])

                num[i]=num[i-1]+1;

            else

                num[i]=1;

        }

        for(i=n-2; i>=0; i--)

        {

            if(ratings[i]>ratings[i+1]&&num[i]<=num[i+1])

                num[i]=num[i+1]+1;

        }

        int res=0;

        for(i=0; i<n; i++)

            res+=num[i];

        return res;

    }

};



int main()

{

    vector<int> ratings= {2,3,5,2,7,8,7,5,6,4};

    Solution s;

    cout<<s.candy(ratings)<<endl;

}

 

 

你可能感兴趣的:(ca)