原题网址:https://leetcode.com/problems/candy/
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?
方法:两个指针,往返追逐。
public class Solution {
public int candy(int[] ratings) {
if (ratings == null || ratings.length == 0) return 0;
if (ratings.length == 1) return 1;
int[] candy = new int[ratings.length];
candy[0] = 1;
// 最近的最高点
int high = 0;
for(int i=1; i<ratings.length; i++) {
if (ratings[i-1] <= ratings[i]) {
int adjust = 1;
for(int j=i-1; j>high; j--, adjust++) candy[j] = adjust;
candy[high] = Math.max(candy[high], adjust);
candy[i] = ratings[i-1]<ratings[i]? candy[i-1]+1:1;
high = i;
}
}
int adjust = 1;
for(int j=ratings.length-1; j>high; j--, adjust++) candy[j] = adjust;
candy[high] = Math.max(candy[high], adjust);
int sum = 0;
for(int i=0; i<ratings.length; i++) sum+=candy[i];
return sum;
}
}