您的位置:首页 > 编程语言 > Go语言

Candy

2014-01-28 01:22 585 查看


Candy

 Total Accepted: 5341 Total
Submissions: 32340My Submissions

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?

从ratings的左往右扫,如果右边的ratings > 左边的rating, 右边的candy = max(右边的candy, 左边的candy +1).
从ratings的右往左扫,如果左边的ratings > 右边的rating, 左边的candy = max(左边的candy, 右边的candy +1).
加总

O(N) time, O(N) space.

public class Solution {
public int candy(int[] ratings) {
int[] candy = new int[ratings.length];
for (int i = 1; i < ratings.length; i++) {
if (ratings[i] > ratings[i - 1]) candy[i] = Math.max(candy[i],candy[i - 1] + 1);
}
int sum = 0;
for (int i = ratings.length - 1; i >= 1; i--) {
if (ratings[i - 1] > ratings[i]) candy[i - 1] = Math.max(candy[i-1],candy[i] + 1);
sum += candy[i];
}
sum+= candy[0];
return sum + candy.length;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm leetcode