您的位置:首页 > 其它

leetcode-Candy

2014-09-25 16:52 309 查看
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;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: