-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCandy.java
More file actions
36 lines (30 loc) · 884 Bytes
/
Copy pathCandy.java
File metadata and controls
36 lines (30 loc) · 884 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
28
29
30
31
32
33
34
35
36
class Solution {
public int candy(int[] ratings) {
int n = ratings.length;
int totalCandies = n;
int i = 1;
while (i < n) {
if (ratings[i] == ratings[i - 1]) {
i++;
continue;
}
int currentPeak = 0;
while (i < n && ratings[i] > ratings[i - 1]) {
currentPeak++;
totalCandies += currentPeak;
i++;
}
if (i == n) {
return totalCandies;
}
int currentValley = 0;
while (i < n && ratings[i] < ratings[i - 1]) {
currentValley++;
totalCandies += currentValley;
i++;
}
totalCandies -= Math.min(currentPeak, currentValley);
}
return totalCandies;
}
}