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

递归版

  1. // Candy
  2. // 备忘录法,时间复杂度O(n),空间复杂度O(n)
  3. // java.lang.StackOverflowError
  4. public class Solution {
  5. public int candy(int[] ratings) {
  6. final int[] f = new int[ratings.length];
  7. int sum = 0;
  8. for (int i = 0; i < ratings.length; ++i)
  9. sum += solve(ratings, f, i);
  10. return sum;
  11. }
  12. int solve(int[] ratings, int[] f, int i) {
  13. if (f[i] == 0) {
  14. f[i] = 1;
  15. if (i > 0 && ratings[i] > ratings[i - 1])
  16. f[i] = Math.max(f[i], solve(ratings, f, i - 1) + 1);
  17. if (i < ratings.length - 1 && ratings[i] > ratings[i + 1])
  18. f[i] = Math.max(f[i], solve(ratings, f, i + 1) + 1);
  19. }
  20. return f[i];
  21. }
  22. }

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