您的位置:首页 > 其它

[LeetCode] Candy

2015-07-27 00:32 381 查看
Well, you may need to run some examples to have the intuition for the answer since we only require children with higher rating get more candies than their neighbors, not all those with lower ratings.

The following code is taken from this link. It involves two-pass scan to ensure the above condition. You will get it after running some examples, like modifying the code and check the wrong cases :-)

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