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?
class Solution { public: int candy(vector<int> &ratings) { int sum=0; int size=ratings.size(); vector<int> candy(size, 1); //从左到右检查每个孩子的左邻居 for(int i=1; i<size; i++){ if(ratings[i]>ratings[i-1]) candy[i]=candy[i-1]+1; } //从右到左检查每个孩子的右邻居 for(int i=size-2; i>=0; i--){ if(ratings[i]>ratings[i+1] && candy[i]<=candy[i+1]) candy[i]=candy[i+1]+1; } //计算饼干数 for(int i=0; i<size; i++) sum+=candy[i]; return sum; } };
LeetCode: Candy [135],布布扣,bubuko.com
原文地址:http://blog.csdn.net/harryhuang1990/article/details/34533335