首页 > 其他 > 详细

[LeetCode] Candy

时间:2015-07-27 01:45:36      阅读:269      评论:0      收藏:0      [点我收藏+]

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 :-)

 1 class Solution {
 2 public:
 3     int candy(vector<int>& ratings) {
 4         int n = ratings.size();
 5         vector<int> candies(n, 1);
 6         for (int i = 1; i < n; i++)
 7             if (ratings[i] > ratings[i - 1])
 8                 candies[i] = candies[i - 1] + 1;
 9         for (int i = n - 1; i > 0; i--)
10             if (ratings[i - 1] > ratings[i])
11                 candies[i - 1] = max(candies[i - 1], candies[i] + 1);
12         int total = 0;
13         for (int i = 0; i < n; i++)
14             total += candies[i];
15         return total;
16     }
17 };

 

[LeetCode] Candy

原文:http://www.cnblogs.com/jcliBlogger/p/4679083.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!