LeetCode135:Candy

mickole發表於2014-02-18

題目:

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;
}

相關文章