Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created June 4, 2015 20:01
Show Gist options
  • Save cangoal/86912a9acf0854a1655f to your computer and use it in GitHub Desktop.
Save cangoal/86912a9acf0854a1655f to your computer and use it in GitHub Desktop.
LeetCode - Candy
//
public int candy(int[] ratings) {
if(ratings == null || ratings.length == 0) return 0;
int[] candy = new int[ratings.length];
candy[0] = 1;
for(int i=1; i<candy.length; i++){
if(ratings[i] > ratings[i-1]){
candy[i] = candy[i-1] + 1;
} else {
candy[i] = 1;
}
}
candy[candy.length -1] = Math.max(1, candy[candy.length-1]);
int total = candy[candy.length-1];
for(int i=candy.length - 2; i >= 0; i--){
if(ratings[i+1] < ratings[i]){
candy[i] = Math.max(candy[i+1] + 1, candy[i]);
}
total += candy[i];
}
return total;
}
//
public int candy(int[] ratings) {
if(ratings==null || ratings.length==0) return 0;
int[] nums = new int[ratings.length];
nums[0] = 1;
for(int i=1; i<ratings.length; i++){
if(ratings[i]>ratings[i-1]){
nums[i] = nums[i-1]+1;
}else{
nums[i] = 1;
}
}
int res = nums[ratings.length-1];
for(int i=ratings.length-2; i>=0; i--){
int cur = 1;
if(ratings[i] > ratings[i+1]){
cur = nums[i+1]+1;
}
res += Math.max(cur, nums[i]);
nums[i] = cur;
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment