Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Question:
Each child has a score.
You give the candy to these children according to the following rules:
1. Each child has at least one sugar.
2. Children with higher scores have more sweets than their neighbors.
What is the minimum number of sweets you can split.
Algorithm analysis:
* Based on the question, the idea can be as follows:
* Initialize the array dp. The array members are all 1. Each child first allocates a candy.
* Traverse from left to right. If the I-th child is higher than the I-1 child, dp [I] = dp [I-1] + 1
* Traverse from the right to the left. If the I-th child is higher than the I + 1 child and has less candy than the I + 1 child, dp [I] = dp [I + 1] + 1
* The algorithm complexity implemented in this way is O (n)
Overall idea diagram below reference blog http://blog.csdn.net/lanxu_yy/article/details/17752273
AC code:
public class Solution{ public int candy(int[] ratings) { if (ratings == null || ratings.length == 0) return 0; ArrayList
dp = new ArrayList
(); 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.get(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; }}