Skip to content

Commit 7090831

Browse files
committed
分糖果
1 parent 9f2261b commit 7090831

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,7 @@
212212
- [Greedy](/algorithm/LeetCode/Greedy.md)
213213
- [Jump Game](/algorithm/LeetCode/Greedy/Jump-Game.md)
214214
- [Gas Station](/algorithm/LeetCode/Greedy/Gas-Station.md)
215+
- [Candy](/algorithm/LeetCode/Greedy/Candy.md)
215216

216217
## 设计模式
217218

algorithm/LeetCode/Greedy/Candy.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
## 一、题目
2+
3+
> There are N children standing in a line. Each child is assigned a rating value.
4+
>
5+
> You are giving candies to these children subjected to the following requirements:
6+
>
7+
> 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?
8+
9+
*N* 个小孩站成一列。每个小孩有一个评级。
10+
11+
按照以下要求,给小孩分糖果:
12+
13+
- 每个小孩至少得到一颗糖果。
14+
- 评级越高的小孩可以比他相邻的两个小孩得到更多的糖果。
15+
16+
需最少准备多少糖果?
17+
18+
## 二、解题思路
19+
20+
首先我们会给每个小朋友一颗糖果,然后从左到右,假设第i个小孩的等级比第i - 1个小孩高,那么第i的小孩的糖果数量就是第i - 1个小孩糖果数量在加一。再我们从右到左,如果第i个小孩的等级大于第i + 1个小孩的,同时第i个小孩此时的糖果数量小于第i + 1的小孩,那么第i个小孩的糖果数量就是第i + 1个小孩的糖果数量加一。
21+
22+
## 三、解题代码
23+
24+
```java
25+
public class Solution {
26+
public int candy(int[] ratings) {
27+
if(ratings == null || ratings.length == 0) {
28+
return 0;
29+
}
30+
31+
int[] count = new int[ratings.length];
32+
Arrays.fill(count, 1);
33+
int sum = 0;
34+
for(int i = 1; i < ratings.length; i++) {
35+
if(ratings[i] > ratings[i - 1]) {
36+
count[i] = count[i - 1] + 1;
37+
}
38+
}
39+
40+
for(int i = ratings.length - 1; i >= 1; i--) {
41+
sum += count[i];
42+
if(ratings[i - 1] > ratings[i] && count[i - 1] <= count[i]) { // second round has two conditions
43+
count[i-1] = count[i] + 1;
44+
}
45+
}
46+
sum += count[0];
47+
return sum;
48+
}
49+
}
50+
```
51+

0 commit comments

Comments
 (0)