题意:

image.png

解题思路:

  1. 思路:
  2. 1. 从左到右依次遍历,如果[右边元素大于左边元素]ratings[i] > ratings[i-1],则当前评分高于左侧,则将d[i] = d[i - 1] + 1
  3. 2. 从右向左遍历,如果左边元素大于右边元素,则取这轮的候选值d[i+1] + 1跟上一轮的d[i]对比,取max即可; => max(d[i], d[i+1] + 1),同时更新max

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param Integer[] $ratings
  4. * @return Integer
  5. */
  6. function candy($ratings) {
  7. if (empty($ratings) || count($ratings) == 0) return 0;
  8. $n = count($ratings);
  9. $d = array_fill(0, $n, 0);
  10. $d[0] = 1;
  11. for ($i = 1; $i < $n; $i++) {
  12. if ($ratings[$i] > $ratings[$i - 1]) {
  13. $d[$i] = $d[$i - 1] + 1;
  14. } else {
  15. $d[$i] = 1;
  16. }
  17. }
  18. $sum = $d[$n - 1];
  19. for ($i = $n - 2; $i >= 0; $i--) {
  20. if ($ratings[$i] > $ratings[$i + 1]) {
  21. $d[$i] = max($d[$i], $d[$i + 1] + 1);
  22. }
  23. $sum += $d[$i];
  24. }
  25. return $sum;
  26. }
  27. }

GO代码实现:

  1. func candy(ratings []int) int {
  2. n := len(ratings)
  3. d := make([]int, n)
  4. d[0] = 1
  5. for i := 1; i < n; i++ {
  6. if ratings[i] > ratings[i-1] {
  7. d[i] = d[i-1] + 1
  8. } else {
  9. d[i] = 1
  10. }
  11. }
  12. sum := d[n - 1]
  13. for i := n -2; i >= 0; i-- {
  14. if ratings[i] > ratings[i+1] {
  15. d[i] = max(d[i], d[i+1] + 1)
  16. }
  17. sum += d[i]
  18. }
  19. return sum
  20. }
  21. func max(a, b int) int {
  22. if a > b {
  23. return a
  24. }
  25. return b
  26. }