| 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 | } |
nothing calls this directly
no outgoing calls
no test coverage detected