LeetCode135: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,否则糖果数为1

第二遍:从后往前扫描,如果当前元素i的值大于i+1位置的值,则比较两者目前的糖果数,如果i小孩获得的糖果数大于第i+1个小孩获得糖果数+1,则不变,否则,将i小孩糖果数置为第i+1个小孩糖果数+1.

实现代码:

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    int candy(vector<int> &ratings) {
        int len = ratings.size();
        if(len == 0 || len == 1)
            return len;
        int *c = new int[len];
        c[0] = 1;
        for(int i = 1; i < len; i++)
            if(ratings[i] > ratings[i-1])
                c[i] = c[i-1] + 1;
            else
                c[i] = 1;
        int minCandy = c[len-1];
        for(int i = len-2; i >= 0; i--)
        {
            if(ratings[i] > ratings[i+1])
                c[i] = max(c[i], c[i+1] + 1);
            minCandy += c[i];            
        }
        return minCandy;
        
    }
};

int main(void)
{
    int ratings[] = {5,8,2,4,9,5,4};
    int len = sizeof(ratings) / sizeof(ratings[0]);
    vector<int> ratVec(ratings, ratings+len);
    Solution solution;
    int ret = solution.candy(ratVec);
    cout<<ret<<endl;
    return 0;
}
posted @ 2014-02-18 20:47  mickole  阅读(320)  评论(0编辑  收藏  举报