您的位置:首页 > 其它

135. Candy

2015-04-19 11:05 155 查看
题目:

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?

链接: http://leetcode.com/problems/candy/

题解:

贪婪法,O(n) space的比较简单,可以左右各来一遍,然后加起来。 不过要尝试更好的公司,还需要练习O(1) space的解法。二刷时再解决。

Time Complexity - O(n),Space Complexity - O(n)。

public class Solution {
public int candy(int[] ratings) {
if(ratings == null || ratings.length == 0)
return 0;
int len = ratings.length;
int[] candies = new int[len];
candies[0] = 1;

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

int sum = candies[len - 1];

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

return sum;
}
}


Reference:
https://leetcode.com/discuss/76/does-anyone-have-a-better-idea https://leetcode.com/discuss/43581/solutions-given-explanation-time-with-space-other-with-space https://leetcode.com/discuss/16463/a-simple-solution https://leetcode.com/discuss/8501/my-accepted-o-n-o-1-solution https://leetcode.com/discuss/23835/one-pass-constant-space-java-solution
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: