您的位置:首页 > 其它

LeetCode 135. Candy(糖果)

2016-05-27 00:22 435 查看
原题网址: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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: