-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmincandy.java
More file actions
41 lines (28 loc) · 833 Bytes
/
mincandy.java
File metadata and controls
41 lines (28 loc) · 833 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
37
38
39
import java.util.Arrays;
public class mincandy {
public int minCandy(int arr[]) {
// code here
int n = arr.length;
int[] candies = new int[n];
// Step 1: Everyone gets at least 1 candy
Arrays.fill(candies, 1);
// Step 2: Left to Right
for (int i = 1; i < n; i++) {
if (arr[i] > arr[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
// Step 3: Right to Left
for (int i = n - 2; i >= 0; i--) {
if (arr[i] > arr[i + 1]) {
candies[i] = Math.max(candies[i], candies[i + 1] + 1);
}
}
// Step 4: Sum candies
int total = 0;
for (int c : candies) {
total += c;
}
return total;
}
}