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|Candy
- [Leetcode 135, Hard] Candy
- [LeetCode] Candy
- Leetcode_candy
- LeetCode:Candy
- [leetcode]Candy @ Python
- LeetCode题解:Candy
- 【leetcode】Candy
- Leetcode -- Candy
- LeetCode题解:Candy
- LeetCode: Candy
- Candy - LeetCode
- LeetCode: Candy
- 6 Candy_Leetcode
- [LeetCode]Candy
- Leetcode135(Candy)
- LeetCode - Candy
- [Leetcode][python]Candy
- LeetCode || Candy
- leetcode -- Candy