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

Candy

时间:2015-05-16 20:29:29      阅读:156      评论: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?

分析:分糖果。每个小孩必须有一个糖果,ratings值大的孩子比他的邻居分得的糖果数要多。

自己在纸上画一画,从两边开始分别扫描,分段进行糖果分发。

从左边开始,假设可以找到x个连续递增的区间;从右边开始,假设可以找到y个连续递增的区间,那么答案就是x + y个区间糖果数量累加的结果。

用时:37ms

 1 class Solution {
 2 public:
 3     int candy(vector<int>& ratings) {
 4         vector<int> record(ratings.size(), 1);
 5         
 6         for(int i = 1, increase = 1; i < ratings.size(); i++){
 7             if(ratings[i] > ratings[i - 1]) record[i] = ++increase;
 8             else increase = 1;
 9         }
10         
11         for(int j = ratings.size() - 2, increase = 1; j >= 0; j--){
12             if(ratings[j] > ratings[j + 1]) record[j] = max(++increase, record[j]);
13             else increase = 1;
14         }
15         
16         int result = 0;
17         for(int i = 0; i < ratings.size(); i++) result += record[i];
18         
19         return result;
20     }
21 };

 

Candy

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4508497.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!