2014年4月27日 星期日

[LeetCode] Candy

Problem:
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:O(n)
public class Solution {
    public int candy(int[] ratings) {
        int len = ratings.length;
        if(len == 0 || len == 1)    
          return len;
        int min = len;
        int[] candies = new int[len];
        int cur = 0;
        for(int i = 1; i < len; i++) {
            if(ratings[i - 1] < ratings[i])
                cur++;
            else
                cur = 0;
            candies[i] = cur;
        }
        cur = 0;
        for(int i = len - 2; i >= 0; i--) {
            if(ratings[i] > ratings[i + 1])
                cur++;
            else
                cur = 0;
          min += Math.max(candies[i], cur);
        }
        min += candies[len - 1];
        return min;
    }
}
Key Concept: Look forward and look backword and get the max one

沒有留言:

張貼留言