Title:
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?
Test Instructions:
n A child stands in a column. Every child has a score.
You assign these candies to these children according to the following rules:
1. Each child has at least one sugar.
2. Children with high scores have more candies than their neighbours ' children.
What is the minimum number of candies that you can separate?
Algorithm Analysis:
* According to test instructions, ideas can be as follows:
* Initialize array DP, array members are 1, each child assigns a candy first
* Traverse from left to right, if the first child is higher than the i-1 child, then dp[i] = dp[i-1] + 1
* Traverse from right to left, if I child is taller than 1 child and candy is less than i+1 candy, then dp[i] = dp[i + 1] + 1
* This idea realizes the algorithm complexity is O (n)
The overall idea is as follows reference blog http://blog.csdn.net/lanxu_yy/article/details/17752273
AC Code:
<span style= "Font-family:microsoft yahei;font-size:10px;" >public class solution{public int Candy (int[] ratings) { if (ratings = = NULL | | ratings.length = = 0) r Eturn 0; arraylist<integer> DP = new arraylist<integer> (); for (int i = 0; i < ratings.length; i++) Dp.add (i, 1); for (int i = 1; i < ratings.length; i++) if (Ratings[i] > ratings[i-1]) dp.set (i, Dp.get (i-1) + 1);
for (int i = ratings.length-2; I >= 0; i--) if (Ratings[i] > ratings[i + 1] && dp.get (i) <= dp.ge T (i + 1)) Dp.set (i, Dp.get (i + 1) + 1); int res = 0; for (int i = 0; i < dp.size (); i++) res + = Dp.get (i); return res; }} </span>
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Candy