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. // Candy
  2. // 时间复杂度O(n),空间复杂度O(n)
  3. class Solution {
  4. public:
  5. int candy(vector<int> &ratings) {
  6. const int n = ratings.size();
  7. vector<int> increment(n);
  8. // 左右各扫描一遍
  9. for (int i = 1, inc = 1; i < n; i++) {
  10. if (ratings[i] > ratings[i - 1])
  11. increment[i] = max(inc++, increment[i]);
  12. else
  13. inc = 1;
  14. }
  15. for (int i = n - 2, inc = 1; i >= 0; i--) {
  16. if (ratings[i] > ratings[i + 1])
  17. increment[i] = max(inc++, increment[i]);
  18. else
  19. inc = 1;
  20. }
  21. // 初始值为n,因为每个小朋友至少一颗糖
  22. return accumulate(&increment[0], &increment[0]+n, n);
  23. }
  24. };

递归版

  1. // Candy
  2. // 备忘录法,时间复杂度O(n),空间复杂度O(n)
  3. // @author fancymouse (http://weibo.com/u/1928162822)
  4. class Solution {
  5. public:
  6. int candy(const vector<int>& ratings) {
  7. vector<int> f(ratings.size());
  8. int sum = 0;
  9. for (int i = 0; i < ratings.size(); ++i)
  10. sum += solve(ratings, f, i);
  11. return sum;
  12. }
  13. int solve(const vector<int>& ratings, vector<int>& f, int i) {
  14. if (f[i] == 0) {
  15. f[i] = 1;
  16. if (i > 0 && ratings[i] > ratings[i - 1])
  17. f[i] = max(f[i], solve(ratings, f, i - 1) + 1);
  18. if (i < ratings.size() - 1 && ratings[i] > ratings[i + 1])
  19. f[i] = max(f[i], solve(ratings, f, i + 1) + 1);
  20. }
  21. return f[i];
  22. }
  23. };

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/linear-list/array/candy.html