两遍遍历,使得左右邻居都合法
1 public class Solution { 2 public int candy(int[] ratings) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 int[] candy = new int[ratings.length]; 6 int count = 0; 7 candy[0] = 1; 8 for(int i = 1; i < candy.length; i++) 9 { 10 if(ratings[i] > ratings[i-1]) 11 candy[i] = candy[i-1]+1; 12 else 13 candy[i] = 1; 14 } 15 for(int i = candy.length - 2; i>= 0; i--) 16 { 17 if(ratings[i] > ratings[i + 1]) 18 candy[i] = Math.max(candy[i], candy[i+1]+1); 19 } 20 for(int i = 0; i < candy.length; i++) 21 count += candy[i]; 22 return count; 23 } 24 }