题目:
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?
解法及分析参考: http://www.cnblogs.com/felixfang/p/3620086.html
class Solution {
public:
//时间复杂度为O(n),空间复杂度为O(1)
int candy(vector<int> &ratings) {
int n = ratings.size();
if (n == 0)
return 0;
int res = 0, pre = 1, cur;
//mark记录严格递减序列的开始
int mark = pre;
//len表示递减序列的长度
int len = 0;
res++;
for (int i = 1; i < n; i++) {
if (ratings[i] < ratings[i - 1]) {
len++;
if (len >= mark)
res++;
res += len;
pre = 1;
}
else {
if (ratings[i] > ratings[i - 1])
cur = pre + 1;
else
cur = 1;
res += cur;
len = 0;
pre = cur;
mark = pre;
}
}
return res;
}
};
本文介绍了一个算法问题——如何以最少的糖果数量满足每个孩子的糖果需求,确保评分高的孩子比邻居获得更多的糖果。通过一个时间复杂度为O(n)且空间复杂度为O(1)的C++实现方案来解决该问题。
1204

被折叠的 条评论
为什么被折叠?



