排排坐分果果,这道题还是蛮难想的,答案忘了从哪里看的了
public int candy(int[] ratings) { if(ratings == null) return 0; int len = ratings.length; int res = 0; if(len==1) return 1; int [] lf = new int[len]; int [] rt = new int[len]; lf[0]=1; for(int i=1;i<len;i++){ if(ratings[i]>ratings[i-1]){ lf[i] = lf[i-1]+1; }else lf[i] = 1; } rt[len-1] = lf[len-1]; for(int j=len-2;j>=0;j--){ if(ratings[j]>ratings[j+1]){ rt[j] = rt[j+1]+1; }else rt[j]=1; } for(int i=0;i<len;i++){ res+=Math.max(rt[i],lf[i]); } return res; }
时间: 2024-10-13 21:23:45