您的位置:首页 > 其它

Candy - Leetcode

2015-02-17 08:30 337 查看
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">public class Solution {</span>
public int candy(int[] ratings) {
int result=0;
int[] helper = new int[ratings.length];
for(int i=1,num=1; i<ratings.length; i++){
if(ratings[i]>ratings[i-1])
helper[i] = num++;
else
num=1;
}

for(int i=ratings.length-2,num=1; i>=0; i--)
{
if(ratings[i]>ratings[i+1])
helper[i] = Math.max(num++, helper[i]);
else
num=1;
}

for(int i=0; i<helper.length; i++)
result += (helper[i]+1);
return result;
}
}


分析:

遍历的方法:从左到右找出相对于左边的大值,分别递增标志出来; 从右到左找出相对于右边的大值,分别递增标志出来。如果遇到递减的,则不标志。最后累计并实现至少有一个的条件。

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?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: