Search This Blog

Saturday, October 26, 2013

LeetCode: 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?

class Solution {
public:
    int candy(vector<int> &ratings) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        vector<int> candies(ratings.size());
        for (int i = 0; i < ratings.size(); ++i) {
            if (i > 0 && ratings[i] > ratings[i-1]) {
                candies[i] = candies[i-1]+1;
            }
        }
        int res = ratings.size() > 0 ?
            ratings.size() + candies[ratings.size()-1] : ratings.size(); 
        for (int i = ratings.size()-2; i>=0; --i) {
            if (ratings[i] > ratings[i+1]) {
                candies[i] = candies[i] < candies[i+1]+1 ? 
                    candies[i+1]+1 : candies[i];
            }
            res += candies[i];
        }
        return res;
    }
};

1 comment:

Yi Wang said...

请问楼主能否看下我的代码,也是O(N)复杂度,但是就是超时。。。
http://blog.csdn.net/whuwangyi/article/details/14633977
多谢!