【LeetCode】135. Candy

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?

 

左右各遍历一次,依据前一个位置的candy数计算当前位置需要的最小candy数(最少为1)

由于两次遍历的结果都要满足,因此对同一位置取max即可。

class Solution {
public:
    int candy(vector<int>& ratings) {
        if(ratings.empty())
            return 0;
        int n = ratings.size();
        vector<int> left(n, 1);
        for(int i = 1; i < n; i ++)
        {
            if(ratings[i] > ratings[i-1])
                left[i] = left[i-1] + 1;
        }
        vector<int> right(n, 1);
        int sum = max(left[n-1], right[n-1]);
        for(int i = n-2; i >= 0; i --)
        {
            if(ratings[i] > ratings[i+1])
                right[i] = right[i+1] + 1;
            sum += max(left[i], right[i]);
        }
        return sum;
    }
};

 

posted @ 2014-11-22 20:09  陆草纯  阅读(144)  评论(0编辑  收藏  举报