image.png

解法

两个数组

image.png

  1. public int candy(int[] ratings) {
  2. int sum = 0;
  3. int n = ratings.length;
  4. int[] left2right = new int[n];
  5. int[] right2left = new int[n];
  6. Arrays.fill(left2right, 1);
  7. Arrays.fill(right2left, 1);
  8. for(int i=1;i<n;i++)
  9. if(ratings[i]>ratings[i-1])
  10. left2right[i]=left2right[i-1]+1;
  11. for(int i=n-2;i>=0;i--)
  12. if(ratings[i]>ratings[i+1])
  13. right2left[i]=right2left[i+1]+1;
  14. for(int i=0;i<n;i++)
  15. sum+=Math.max(right2left[i],left2right[i] );
  16. return sum;
  17. }