Candy
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.
1 public class Solution { 2 public int candy(int[] ratings) { 3 int len = ratings.length; 4 if(len<=0) return 0; 5 int candy[] = new int[len]; 6 int left = 1; 7 for(int i=0;i<len;i++){ 8 if(i>0&&ratings[i]>ratings[i-1]){ 9 left ++; 10 }else{ 11 left = 1; 12 } 13 candy[i] = left; 14 } 15 int right = 1; 16 for(int i=len-1;i>=0;i--){ 17 if(i<len-1&&ratings[i]>ratings[i+1]){ 18 right++; 19 }else{right=1;} 20 candy[i] = Math.max(candy[i],right); 21 22 } 23 int sum = 0; 24 for(int i=0;i<len;i++){ 25 sum+=candy[i]; 26 } 27 return sum; 28 } 29 }