您的位置:首页 > 其它

[LeetCode] 130: Candy

2017-09-10 20:53 369 查看
[Problem]

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?


[Solution]

class Solution {
public:
int candy(vector<int> &ratings) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(ratings.size() == 0) return 0;

// initial
int dp[ratings.size()];
for(int i = 0; i < ratings.size(); ++i)dp[i] = 1;

// dp
for(int i = 1; i < ratings.size(); ++i){
if(ratings[i] > ratings[i-1]){
dp[i] = max(dp[i], dp[i-1] + 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);
}
}

// get result
int res = 0;
for(int i = 0; i < ratings.size(); ++i){
res += dp[i];
}
return res;
}
};
说明:版权所有,转载请注明出处。Coder007的博客
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: