-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCandy.java
More file actions
34 lines (28 loc) · 1.04 KB
/
Candy.java
File metadata and controls
34 lines (28 loc) · 1.04 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
class Solution {
public int candy(int[] ratings) {
int n = ratings.length;
int[] candies = new int[n];
// Initialize all children with 1 candy
for (int i = 0; i < n; i++) {
candies[i] = 1;
}
// Traverse from left to right, ensuring higher rating children get more candies than their left neighbor
for (int i = 1; i < n; i++) {
if (ratings[i] > ratings[i-1]) {
candies[i] = candies[i-1] + 1;
}
}
// Traverse from right to left, ensuring higher rating children get more candies than their right neighbor
for (int i = n-2; i >= 0; i--) {
if (ratings[i] > ratings[i+1] && candies[i] <= candies[i+1]) {
candies[i] = candies[i+1] + 1;
}
}
// Calculate the total number of candies
int totalCandies = 0;
for (int candy : candies) {
totalCandies += candy;
}
return totalCandies;
}
}