您的位置:首页 > 其它

LeetCode-135.Candy

2016-06-06 17:03 232 查看
https://leetcode.com/problems/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?

跟题LeetCode-42.Trapping Rain Water 类似,使用两次动态规划

public int Candy(int[] ratings)
{
int n = ratings.Length;
if (n < 2)
return 1;
int[] left = new int
;
left[0] = 1;
for (int i = 1; i < n; i++)
{
left[i] = 1;
if (ratings[i] > ratings[i - 1])
left[i] += left[i - 1];
}
int[] right = new int
;
right[n - 1] = left[n - 1];
int res= left[n - 1];
for (int i = n-2; i >=0; i--)
{
right[i] = 1;
if (ratings[i] > ratings[i + 1])
right[i] += right[i + 1];
res += Math.Max(left[i], right[i]);
}
return res;
}


优化减少空间,省去right数组

public int Candy(int[] ratings)
{
int n = ratings.Length;
if (n < 2)
return 1;
int[] left = new int
;
left[0] = 1;
for (int i = 1; i < n; i++)
{
left[i] = 1;
if (ratings[i] > ratings[i - 1])
left[i] += left[i - 1];
}
int res= left[n - 1],right;
for (int i = n-2; i >=0; i--)
{
right = 1;
if (ratings[i] > ratings[i + 1])
right += left[i + 1];
res += Math.Max(left[i], right);
left[i] = right;
}
return res;
}


参考 http://blog.csdn.net/linhuanmars/article/details/21424783
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 动态规划