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?

思路:关键是找谷底,令谷底为1,然后谷底左右递增。

其实就是左扫一遍,右扫一遍数组, ratings递增就+1, 否则就set 1.

然后取最大值。

AC代码:

class Solution {
public:
    int candy(vector<int>& ratings) {
        int n = ratings.size();
        if(n==0) return 0;
        vector<int>l(n, 0);
        vector<int>r(n, 0);
        l[0] = 1;
        r[n-1] = 1;
        for(int i=1, j=n-2; i<n && j>=0; i++, j--)
        {
            if(ratings[i] > ratings[i-1])
                l[i] = l[i-1]+1;
            else l[i] = 1;
            if(ratings[j]>ratings[j+1])
                r[j] = r[j+1]+1;
            else r[j] = 1;
        }
        int ans = 0;
        for(int i=0; i<n; i++)
        {        
            ans += max(l[i], r[i]);
        }
        return ans;
    }
};

 

posted @ 2016-04-02 23:37  Gu Feiyang  阅读(243)  评论(0)    收藏  举报