题目:
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;
}
};