Sunday, January 11, 2015

LeetCode 135: 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?
public class Solution {
    public int candy(int[] ratings) {
        // For this question, we only consider two sequences: increasing sequence and decreasing sequence.
        // For ascending sequence (ratings[i] > ratings[i-1]), assign ins[i] = ins[i-1] + 1;
        // For descending sequence (ratings[i] > ratings[i+1]), assign des[i] = des[i+1] + 1.
        // Finally get max of two assignments.
        int n = ratings.length;
        
        if (n == 0)
            return 0;
        
        int[] ins = new int[n]; // Increasing sequence assignment
        int[] des = new int[n]; // Decreasing sequence assignment
        
        ins[0] = 1;
        
        for (int i = 1; i < n; i++)
        {
            if (ratings[i] > ratings[i-1])
                ins[i] = ins[i-1]+1;
            else
                ins[i] = 1;
        }
        
        des[n-1] = 1;
        
        for (int i = n-2; i >= 0; i--)
        {
            if (ratings[i] > ratings[i+1])
                des[i] = des[i+1]+1;
            else
                des[i] = 1;
        }
        
        int sum = 0;
        
        for (int i = 0; i < n; i++) 
            sum += Math.max(ins[i], des[i]);

        return sum;
    }
}

No comments:

Post a Comment