标签:
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:
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 };
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/4508497.html