您的位置:首页 > 其它

LeetCode:Candy

2016-05-25 22:42 477 查看


Candy

Total Accepted: 52308 Total
Submissions: 231427 Difficulty: Hard

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?

Subscribe to see which companies asked this question

Hide Tags
Greedy

思路:

1.先给每个小孩分1 个candy;

2.从左往右:如果,左<右,则右边小孩加1颗candy;

2.从右往左:如果,左>右,则左边小孩要比右边的candy多。

java code:

public class Solution {
public int candy(int[] ratings) {

int len = ratings.length;
int[] candies = new int[len];
for(int i=0;i<len;i++) candies[i] = 1;

for(int i=1;i<len;i++) {
if(ratings[i-1] < ratings[i])
candies[i] = candies[i-1] + 1;
}

for(int i=len-1;i>0;i--) {
if(ratings[i-1] > ratings[i])
candies[i-1] = Math.max(candies[i-1], candies[i]+1);
}

int ans = 0;
for(int candy : candies) {
ans += candy;
}

return ans;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: