首页 > ACM题库 > LeetCode > LeetCode-Candy[数组]
2014
11-18

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

标签: Greedy
分析

代码1

// LeetCode, Candy
// 时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
    int candy(vector<int> &ratings) {
        const int n = ratings.size();
        vector<int> increment(n);

        // 左右各扫描一遍
        for (int i = 1, inc = 1; i < n; i++) {
            if (ratings[i] > ratings[i - 1])
                increment[i] = max(inc++, increment[i]);
            else
                inc = 1;
        }

        for (int i = n - 2, inc = 1; i >= 0; i--) {
            if (ratings[i] > ratings[i + 1])
                increment[i] = max(inc++, increment[i]);
            else
                inc = 1;
        }
        // 初始值为n,因为每个小朋友至少一颗糖
        return accumulate(&increment[0], &increment[0]+n, n);
    }
};

代码2

// LeetCode, Candy
// 备忘录法,时间复杂度O(n),空间复杂度O(n)
// @author fancymouse (http://weibo.com/u/1928162822)
class Solution {
public:
    int candy(const vector<int>& ratings) {
        vector<int> f(ratings.size());
        int sum = 0;
        for (int i = 0; i < ratings.size(); ++i)
            sum += solve(ratings, f, i);
        return sum;
    }
    int solve(const vector<int>& ratings, vector<int>& f, int i) {
        if (f[i] == 0) {
            f[i] = 1;
            if (i > 0 && ratings[i] > ratings[i - 1])
                f[i] = max(f[i], solve(ratings, f, i - 1) + 1);
            if (i < ratings.size() - 1 && ratings[i] > ratings[i + 1])
                f[i] = max(f[i], solve(ratings, f, i + 1) + 1);
        }
        return f[i];
    }
};

Java代码:

public class Solution {
    public int candy(int[] ratings) {
        int cntArr[] = new int[ratings.length];
        for(int i=0; i<cntArr.length; i++) cntArr[i]=1;
        for(int i=1; i<cntArr.length; i++){
            if(ratings[i] > ratings[i-1])
                cntArr[i] = cntArr[i-1]+1;
        }
        int ans = cntArr[cntArr.length-1];
        for(int i=cntArr.length-2; i>=0; i--){
            if(ratings[i] > ratings[i+1] && cntArr[i] <= cntArr[i+1])
                cntArr[i] = cntArr[i+1]+1;
            ans += cntArr[i];
        }
        return ans;
        
    }
}

  1. I like your publish. It is great to see you verbalize from the coronary heart and clarity on this essential subject matter can be easily noticed.