class Solution {
public:
int candy(vector<int> &ratings) {
if (ratings.size() == 0)
return 0;
if (ratings.size() == 1) {
return 1;
}
vector<int> candy(ratings.size(), 1);
for (int i = 0; i < ratings.size() - 1; i++) {
//如果右边比左边大
if (ratings[i + 1] > ratings[i])
candy[i + 1] = candy[i] + 1;
}
for (int i = ratings.size() - 1; i >= 1; i--) {
//如果左边比右边大
if (ratings[i - 1] > ratings[i])
candy[i - 1] = max(candy[i - 1], candy[i] + 1);
}
int res = 0;
for (int t : candy) {
res += t;
}
return res;
}
};
135. 分发糖果
最新推荐文章于 2023-09-16 18:55:18 发布