leetcode---candy---dp

来源:互联网 发布:刘德华 知乎 编辑:程序博客网 时间:2024/05/22 10:29

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)     {        int n = ratings.size();        vector<int> dp(n, 0);        dp[0] = 1;        int sum = 1;        if(n == 0)        {            return 0;        }         for(int i=1; i<n; i++)        {            if(ratings[i] > ratings[i-1])            {                dp[i] = dp[i-1] + 1;                sum += dp[i];            }            else if(ratings[i] < ratings[i-1])            {                if(i == 1)                {                    dp[0] = 2;                    dp[1] = 1;                    sum = 3;                }                else                {                    dp[i] = 1;                    int k = i-1;                    if(ratings[k] <= ratings[k-1])                    {                        while(k > 0 && ratings[k] < ratings[k-1] && dp[k]+1 == dp[k-1])                        {                            dp[k] += 1;                            k--;                            sum++;                        }                        dp[k] += 1;                        sum++;                    }                    sum += dp[i];                }            }            else            {                dp[i] = 1;                sum += dp[i];            }        }        return sum;    }};
原创粉丝点击