Candy
Total Accepted: 5859 Total Submissions: 35021There 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.
public class Solution {
public int candy(int[] ratings) {
int cur = 0;
int candy[] = new int[ratings.length];
for(int i=0;i<ratings.length;i++) {
if(i==0 || ratings[i]>ratings[i-1]) {
cur++;
} else {
cur = 1;
}
candy[i] = cur;
}
cur = 0;
for(int i=ratings.length-1;i>=0;i--) {
if(i==ratings.length-1 || ratings[i]>ratings[i+1]) {
cur++;
} else {
cur = 1;
}
candy[i] = Math.max(candy[i], cur);
}
int all = 0;
for(int c : candy) {
all += c;
}
return all;
}
}
public class Solution {
public int candy(int[] ratings) {
if(ratings==null || ratings==null) {
return 0;
}
int[] candy = new int[ratings.length];
for(int i=0;i<ratings.length;i++) {
if(i!=0 && ratings[i] > ratings[i-1]) {
candy[i] = candy[i-1] + 1;
} else {
candy[i] = 1;
}
}
int ret = 0;
for(int i=ratings.length-1;i>=0;i--) {
if(i!=ratings.length-1 && ratings[i]>ratings[i+1]) {
candy[i] = Math.max(candy[i], candy[i+1]+1);
}
ret += candy[i];
}
return ret;
}
}
没有评论:
发表评论