首页 > 其他 > 详细

[LeetCode]Candy

时间:2015-10-18 01:05:36      阅读:286      评论:0      收藏:0      [点我收藏+]

题目描述:(链接)

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?

解题思路:


开辟一个数组记录每个孩子的糖果数,前后两次扫描该数组,改变当前孩子的糖果数目。

 1 class Solution {
 2 public:
 3     int candy(vector<int>& ratings) {
 4         int n = ratings.size();
 5         vector<int> result(n);
 6 
 7         for (int i = 1; i < n; ++i) {
 8             if (ratings[i] > ratings[i - 1]) {
 9                 result[i] = result[i - 1] + 1;
10             }
11         }
12 
13         for (int i = n - 2; i >= 0; --i) {
14             if (ratings[i] > ratings[i + 1]) {
15                 result[i] = (result[i + 1] + 1 > result[i])? result[i + 1] + 1 : result[i];
16             }
17         }
18 
19         int sum = 0;
20         for (int i = 0; i < n; ++i) {
21             sum += result[i];
22         }
23 
24         return sum + n;
25     }
26 };

 

[LeetCode]Candy

原文:http://www.cnblogs.com/skycore/p/4888646.html

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