forked from mengli/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCandy.java
More file actions
38 lines (33 loc) · 1.07 KB
/
Candy.java
File metadata and controls
38 lines (33 loc) · 1.07 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
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?
public class Solution {
public int candy(int[] ratings) {
int[] A = new int[ratings.length];
for (int i = 0; i < A.length; i++) {
A[i] = 1;
}
for (int j = 1; j < A.length; j++) {
check(A, ratings, j);
}
int sum = 0;
for (int k = 0; k < A.length; k++) {
sum += A[k];
}
return sum;
}
private void check(int[] plan, int[] ratings, int start) {
while (start > 0) {
if (ratings[start - 1] > ratings[start] && plan[start - 1] <= plan[start]) {
plan[start - 1] = plan[start] + 1;
} else if (ratings[start - 1] < ratings[start] && plan[start - 1] >= plan[start]) {
plan[start] = plan[start - 1] + 1;
} else {
return;
}
start--;
}
}
}