leetcode-Candy

来源:互联网 发布:青龙取水选股公式源码 编辑:程序博客网 时间:2024/05/22 17:11

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 allocate (vector<int> &r, vector<int> &a, int i, int &n)    {        if(a[i] != 0)return a[i];        int m = 0;        if(i > 0 && r[i] > r[i-1]) m = allocate(r,a,i-1,n);        if(i < n-1 && r[i] > r[i+1]) m =max(m,allocate(r,a,i+1,n));        a[i] = m+1;        return a[i];    }        int candy(vector<int> &ratings) {        int n = ratings.size();        if(n == 0)return 0;        if(n == 1)return 1;        vector<int> nums(n,0);        int ret = 0;                if(ratings[0] < ratings[1]) nums[0] = 1;        if(ratings[n-1] < ratings[n-2]) nums[n-1] = 1;        for(int i = 1; i < n-1; i++)        {            if(ratings[i] < ratings[i-1]&&ratings[i] < ratings[i+1])            {                nums[i] = 1;            }        }                for(int i = 0; i < n; i++)        {            if(nums[i] == 0)            {                (void)allocate(ratings,nums,i,n);            }        }                for(int i = 0; i < n; i++)        {            ret += nums[i];        }                return ret;            }};


0 0
原创粉丝点击