135. Candy
题目
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?
解析
- 这样前后两个遍历结果,思路
- 采用一次遍历实现或者其他动态规划的思路实现
class Solution_135 {
//题意:N个孩子站成一排,每个孩子分配一个分值。给这些孩子派发糖果,满足如下要求:
//每个孩子至少一个
//分值更高的孩子比他的相邻位的孩子获得更多的糖果
//求至少分发多少糖果?
public:
int candy(vector<int> &ratings) {
//采用左右遍历两次方法
const int len = ratings.size();
if (len==1)
{
return len;
}
vector<int> res(len,1);
for (int i = 1; i < ratings.size();i++)
{
if (ratings[i]>ratings[i-1]) //右边大于左边
{
res[i] = res[i - 1] + 1; //分配的糖果数
}
}
int ret = 0;
for (int j = len - 2,ret=res[len-1]; j >= 0;j--) //bug 此处ret当做局部变量,
{
if (ratings[j]>ratings[j+1]&& res[j]<=res[j+1]) //左边大于右边且左边的糖果少于右边的糖果数
{
res[j] = res[j + 1] + 1;
}
ret += res[j];
}
return ret;
}
};
题目来源