友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

135. 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?

Example 1:

Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
             The third child gets 1 candy because it satisfies the above two conditions.

思路分析

从左右两端分两次遍历,分别跟左右两边的数比较,自身大则比对应的糖果多一个。最后,取两次比较中,每个座位对应糖果最大值相加即可。

0135 01
0135 02
0135 03
  • 一刷

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2024-09-20 15:48:40
 */
public int candy(int[] ratings) {
  int[] left = new int[ratings.length];
  int[] right = new int[ratings.length];
  Arrays.fill(left, 1);
  Arrays.fill(right, 1);
  for (int i = 1; i < ratings.length; i++) {
    if (ratings[i - 1] < ratings[i]) {
      left[i] = left[i - 1] + 1;
    }
  }
  for (int i = ratings.length - 2; i >= 0; i--) {
    if (ratings[i] > ratings[i + 1]) {
      right[i] = right[i + 1] + 1;
    }
  }
  int result = 0;
  for (int i = 0; i < ratings.length; i++) {
    result += Math.max(left[i], right[i]);
  }
  return result;
}