赞
踩
分情况考虑一下就好了
1.递增前一个直接+1
2.值不变,直接变成1
3.值减少的时候要注意连续递减了多少个,是否要增加前一位的值
class Solution {
public:
int candy(vector<int>& ratings) {
int sum = 0 ;
int pre = 0 ;
int st = 0 ;
int i = 0 ;
while( i < ratings.size() ){
if( i == 0 ){
sum += 1 ;
pre = 1 ;
st = i ;
}
else if( ratings[i] > ratings[i-1] ){
pre = pre + 1 ;
sum = sum + pre ;
st = i ;
}
else if( ratings[i] == ratings[i-1]){
pre = 1 ;
sum += pre ;
st = i ;
}
else{
int k = i ;
while( k < ratings.size() && ratings[k] < ratings[k-1] ){
k++ ;
}
int m = k - i ;
sum += ( m * (m+1) / 2 );
sum += max( 0, m + 1 - pre );
pre = 1 ;
i = k ;
continue ;
}
i++ ;
}
return sum ;
}
};
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。