Skip to content

Instantly share code, notes, and snippets.

@alice-0-kim alice-0-kim/candy.java
Last active Sep 23, 2019

Embed
What would you like to do?
/**
There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements:
1. Each child must have at least one candy.
2. Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
*/
import java.util.*;
public int candy(int[] ratings) {
int N = ratings.length;
int[] candies = new int[N];
Arrays.fill(candies, 1);
for (int i = 1; i < N; i++) {
if (ratings[i] > ratings[i-1]) {
candies[i] = candies[i-1] + 1;
}
}
for (int i = N-2; i > 0; i--) {
if (ratings[i] > ratings[i+1]) {
candies[i] = candies[i+1] + 1;
}
}
return Arrays.stream(candies).sum();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.