码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Candy

时间:2015-07-27 01:46:41      阅读:92      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!