题目
根据数组权重分配糖果,每个位子至少一个,比旁边高,糖就要多
代码
public class Solution {
public int candy(int[] ratings) {
int[] record = new int[ratings.length];
int n =ratings.length;
record[0]=1;
for(int i=1;i<n;i++){
if(ratings[i]>ratings[i-1]){
record[i]=record[i-1]+1;
}
else{
record[i]=1;
}
}
int total =record[n-1];
for(int i=n-2;i>=0;i--){
if(ratings[i]>ratings[i+1]){
record[i]=Math.max(record[i],record[i+1]+1);
}
total+=record[i];
}
return total;
}
}
思路
很tricky,左边的趋势先计算出按照左边至少的糖果;右边的趋势再计算出最后的结果