标签:
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?
解题思路:用了比较麻烦的方法,遍历两遍数组,第一遍对于确保右边比左边的人拿到的糖果符合条件;第二遍遍历来修正左边对于右边的情况;
#include<iostream> #include<vector> #include<numeric> using namespace std; int candy(vector<int> &ratings) { int ChildrenNum = ratings.size(); vector<int>CandyVector(ChildrenNum, 1); for (int i = 0; i < ChildrenNum-1;++i){ if (ratings[i] < ratings[i + 1]) CandyVector[i + 1] = CandyVector[i] + 1; } for (int i = ChildrenNum-1; i >0; --i){ if (ratings[i] < ratings[i - 1]&&CandyVector[i]>=CandyVector[i-1]) CandyVector[i - 1] = CandyVector[i] + 1; } return accumulate(CandyVector.begin(), CandyVector.end(), 0); }
标签:
原文地址:http://blog.csdn.net/li_chihang/article/details/43485903