-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathCandy.java
More file actions
27 lines (22 loc) · 691 Bytes
/
Candy.java
File metadata and controls
27 lines (22 loc) · 691 Bytes
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
// https://leetcode.com/problems/candy
// T: O(N)
// S: O(N)
import java.util.Arrays;
public class Candy {
public int candy(int[] ratings) {
final int[] candies = new int[ratings.length];
// left pass
for (int i = 1 ; i < ratings.length ; i++) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
// right pass
for (int i = ratings.length - 2 ; i >= 0 ; i--) {
if (ratings[i] > ratings[i + 1]) {
candies[i] = Math.max(candies[i], candies[i + 1] + 1);
}
}
return Arrays.stream(candies).sum() + ratings.length;
}
}