题意
给每个孩子分糖果,如果这个孩子的rating比相邻的孩子高,那么他分到的糖果就要比他多,求最少需要多少糖果。
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:
- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Example 1:
Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
test cases
[3,2,1,1,2,4,3,2,1,0,0]
[1,0,2]
[1,0,2,2,3,4,5,6,7,7,8,9,0,1,2,3,2,1,1,2,1,0]
[3,2,1,1,2,3,2,2,3,4,2,2,1]
[]
[1,2,2,2,1,1,3,1,2,10,20,19,18,17,16,15,4,3,2,1,2,2,1,1,0,1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1,0,10]
[1]
[0]
解1 只遍历一遍即得出结果
时间复杂度O(N)
[3,2,1,1,2,4,3,2,1,0,0]
对这个用例,分法应该为:
[3,2,1,1,2,5,4,3,2,1,1]
过程为:
[1]
[2,1]
[3,2,1]
[3,2,1,1]
[3,2,1,1,2]
[3,2,1,1,2,3]
[3,2,1,1,2,3,1]
[3,2,1,1,2,3,2,1]
[3,2,1,1,2,4,3,2,1]
[3,2,1,1,2,5,4,3,2,1]
[3,2,1,1,2,5,4,3,2,1,1]
思路:维护3个变量:当前高度、前最大高度、当前台阶高度。
如果比前一个孩子分高,
如果是第一次上升,那么当前台阶高度=2,
如果不是第一次上升,那么当前台阶高度++;
结果加上当前台阶高度。
如果比前一个孩子分低,
如果不是第一次下降,那么台阶高度++;
如果是第一次下降,那么台阶高度=1;
结果加上 high < maxHigh ? high : maxHigh + 1;
如果相等,
与前面隔断。
讲不清楚,也很复杂,直接上代码
// Runtime: 2 ms, faster than 95.29% of Java online submissions for Candy.
//Memory Usage: 39.7 MB, less than 16.42% of Java online submissions for Candy.
public int candy(int[] ratings) {
if (ratings == null || ratings.length == 0)
return 0;
int prev = ratings[0];
int sum = 1;
int level = 1;
int high = 1;
int maxHigh = 1;
for (int i = 1; i < ratings.length; i++) {
if (ratings