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?
两遍遍历,使得左右邻居都合法
public class Solution { public int candy(int[] ratings) { int len = ratings.length; int count = 0; int[] candy = new int[len]; candy[0] = 1; for(int i = 1; i < len; i++){ if(ratings[i] > ratings[i-1]){ candy[i] = candy[i-1] +1; }else{ candy[i] = 1; } } for(int i = len-2; i>=0; i--){ if(ratings[i] > ratings[i+1]){ candy[i] = Math.max(candy[i], candy[i+1]+1); } } for(int i = 0; i< candy.length; i++){ count += candy[i]; } return count; }}
TODO------DP : http://fisherlei.blogspot.com/2013/11/leetcode-candy-solution.html