问题描述
解题思路
本题的关键在于,需要一次从前往后的遍历,第一次确定最少糖果数,同时还需要从后往前遍历,再一次确定最少糖果数。
代码
class Solution {
public:
int candy(vector<int>& ratings) {
vector<int> candyVec(ratings.size(), 1);
// 从前向后
for (int i = 1; i < ratings.size(); i++) {
if (ratings[i] > ratings[i - 1]) candyVec[i] = candyVec[i - 1] + 1;
}
// 从后向前
for (int i = ratings.size() - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1] ) {
candyVec[i] = max(candyVec[i], candyVec[i + 1] + 1);
}
}
// 统计结果
int result = 0;
for (int i = 0; i < candyVec.size(); i++) result += candyVec[i];
return result;
}
};
标签:分发,ratings,int,candyVec,candy,result,135,糖果,size
From: https://www.cnblogs.com/zwyyy456/p/16841721.html