Untitled
unknown
plain_text
9 months ago
1.0 kB
4
Indexable
// Candy distribution implementation (from L12)
public static int minCandies(int[] ratings) {
int n = ratings.length;
int[] left = new int[n];
int[] right = new int[n];
// Initialize base cases
left[0] = 1;
right[n-1] = 1;
// Calculate left to right
for (int i = 1; i < n; i++) {
if (ratings[i] > ratings[i-1]) {
left[i] = left[i-1] + 1;
} else {
left[i] = 1;
}
}
// Calculate right to left
for (int i = n-2; i >= 0; i--) {
if (ratings[i] > ratings[i+1]) {
right[i] = right[i+1] + 1;
} else {
right[i] = 1;
}
}
// Calculate final sum
int sum = 0;
for (int i = 0; i < n; i++) {
sum += Math.max(left[i], right[i]);
}
return sum;
}Editor is loading...
Leave a Comment