思路:维护三种趋势,主要对减趋势去处理值大于1或者小于1的情况,处理起来非常复杂
优化:从两边各走一边增序列,增序列好处理。为数组赋初始值1
// 思路:定义三种趋势,up、down、back,分别对应增、减、持平。
// 增趋势不需要返回处理 trend = 1
// 减趋势可能会减到负数,需要返回处理 trend = -1 ,需要维护start和end
// back趋势一直赋1 trend = 0
class Solution {
public int candy(int[] ratings) {
int n = ratings.length;
int candy[] = new int[n];
candy[0] = 1;
int trend = 0;
int start = 0;
int sum = 1;
for(int i=1;i<n;i++){
// 增趋势
if(ratings[i]>ratings[i-1]){
trend = 1;
candy[i] = candy[i-1] + 1;
}else if(ratings[i]<ratings[i-1]){ // 减趋势
if(trend!=-1){ // 转变
start = i-1;
trend = -1;
}
candy[i] = candy[i-1]-1;
if(i+1>=n || ratings[i]<=ratings[i+1]){ // 减趋势结束
if(candy[i]<1) sum += (i-start)*(1-candy[i]); // 补值不包括candy[i]
else if(candy[i]>1) sum += (i-start-1)*(1-candy[i]); // 减值不包括candy[start]和candy[i]
candy[i] = 1;
trend = 0;
}
}else { // 持平
trend = 0;
candy[i] = 1;
}
sum += candy[i];
}
return sum;
}
}
相比之下简介了很多:
// 从两边各处理一遍增序列
class Solution {
public int candy(int[] ratings) {
int len = ratings.length;
int candy[] = new int[len];
Arrays.fill(candy,1);
for(int i=1;i<len;i++){
if(ratings[i]>ratings[i-1])candy[i] = candy[i-1] + 1;
}
for(int i=len-2;i>=0;i--){
if(ratings[i]>ratings[i+1])candy[i] = Math.max(candy[i],candy[i+1]+1);
}
return Arrays.stream(candy).sum();
}
}