-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
32 lines (29 loc) · 782 Bytes
/
Copy pathsolution.java
File metadata and controls
32 lines (29 loc) · 782 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
class Solution {
public int minCandy(int[] arr) {
int n = arr.length;
if (n == 0) return 0;
long total = 1;
int up = 0, down = 0, peak = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > arr[i - 1]) {
up++;
peak = up;
down = 0;
total += 1 + up;
}
else if (arr[i] == arr[i - 1]) {
up = down = peak = 0;
total += 1;
}
else {
down++;
up = 0;
total += 1 + down;
if (down <= peak) {
total--;
}
}
}
return (int) total;
}
}