There is N children standing in a line. Each child is assigned a rating value.
You is giving candies to these children subjected to the following requirements:
- Each child must has at least one candy.
- Children with a higher rating get more candies than their neighbors.
What's the minimum candies you must give?
Problem Solving Ideas:
Two-way climbing problem, from the past, back and forth from the previous sweep again, Java implementation is as follows:
public int candy (int[] ratings) {int sum = 0;int[] Candies = new Int[ratings.length];for (int i = 0; i < ratings.length -1; i++) if (Ratings[i] < Ratings[i + 1]) Candies[i + 1] = Candies[i] + 1;for (int i = ratings.length-2; I >= 0; i--) if (Ratings[i + 1] < Ratings[i]) candies[i] = Math.max (Candies[i], candies[i + 1] + 1); for (int i = 0; i < Candies.lengt H i++) Sum + = 1 + candies[i];return sum;}
Java for Leetcode 135 Candy