Skip to content

Commit 3769853

Browse files
committed
add: Candies
1 parent 0c65784 commit 3769853

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

java/Greedy/Candies.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import java.util.Arrays;
2+
3+
public class Candies {
4+
public int candies(int[] ratings) {
5+
int n = ratings.length;
6+
// Ensure each child starts with 1 candy.
7+
int[] candies = new int[n];
8+
Arrays.fill(candies, 1);
9+
// First pass: for each child, ensure the child has more candies
10+
// than their left-side neighbor if the current child's rating is
11+
// higher.
12+
for (int i = 1; i < n; i++) {
13+
if (ratings[i] > ratings[i - 1]) {
14+
candies[i] = candies[i - 1] + 1;
15+
}
16+
}
17+
// Second pass: for each child, ensure the child has more candies
18+
// than their right-side neighbor if the current child's rating is
19+
// higher.
20+
for (int i = n - 2; i >= 0; i--) {
21+
if (ratings[i] > ratings[i + 1]) {
22+
// If the current child already has more candies than their
23+
// right-side neighbor, keep the higher amount.
24+
candies[i] = Math.max(candies[i], candies[i + 1] + 1);
25+
}
26+
}
27+
return Arrays.stream(candies).sum();
28+
}
29+
}

0 commit comments

Comments
 (0)