您的位置:首页 > 编程语言 > C语言/C++

LeetCode——Candy

2014-05-12 15:55 337 查看


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?

思路:此题采用动态规划算法(dp)。dp[i]表示i child 应该获得的最小糖果。进行两遍扫描,第一遍扫描判断后一个与前一个的大小,然后变化dp[i]。第二遍扫描判断前一个与后一个的大小,然后变化dp[i]。dp的和为最后的结果。

代码:class Solution {
public:
int candy(vector<int> &ratings) {
int ret = 0;
if (ratings.size() == 0)
return ret;
vector<int> dp(ratings.size(), 1);
for (int i = 1; i < ratings.size(); i++)
if (ratings[i] > ratings[i - 1])
dp[i] = dp[i - 1] + 1;

ret = dp[ratings.size() - 1];
for (int i = ratings.size() - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
dp[i] = max(dp[i], dp[i + 1] + 1);
}
ret += dp[i];
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c++