Last active
September 23, 2019 04:48
-
-
Save yehee/0f22a7b20372bcf7f5382c3402cbd969 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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