Friday, February 7, 2014

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.
What is the minimum candies you must give?

Solution:
Draw a rating value curve, say a[i], it has following case:
1. a[i-1] < a[i] <= a[i+1]  --> assign a[i] one more candy than a[i-1]
2. a[i-1] >= a[i] > a[i+1]  --> assign a[i] one more candy than a[i+1]
3. a[i] > a[i-1] and a[i] > a[i+1]. --> assign a[i] max(a[i-1],a[i+1]) to meet the second requirement.
4. a[i-1]==a[i]==a[i+1], keep same.


public class Solution {
    public int candy(int[] ratings) {
        // corner case
        int n = ratings.length;
        if(n == 0)
            return 0;
        
        // initialization
        int[] num = new int[n];
        Arrays.fill(num,1);
        
        // for increasing ratings
        for(int i = 1; i < n; i++){
            if(ratings[i] > ratings[i - 1]){
                num[i] = num[i-1]+1;
            }
        }
        // for decreasing ratings
        for(int i = n-2; i >= 0; i--){
            if(ratings[i] > ratings[i + 1] && num[i] <= num[i+1]){
                    num[i] = num[i+1]+1;
            }
        }
        
        // count all
        int sum = 0;
        for(int i : num)
            sum += i;
        return sum;
    }
}

No comments:

Post a Comment