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?
Solution:
进行两次扫描,一次从左往右,一次从右往左。
第一次扫描的时候维护对于每一个小孩左边所需要最少的糖果数量,存入数组对应元素中,
第二次扫描的时候维护右边所需的最少糖果数,并且比较将左边和右边大的糖果数量存入结果数组对应元素中。
这样两遍扫描之后就可以得到每一个所需要的最最少糖果量,从而累加得出结果。
方法只需要两次扫描,所以时间复杂度是O(2*n)=O(n)。空间上需要一个长度为n的数组,空间复杂度是O(n)。
public class Solution { public int candy(int[] ratings) { if(ratings == null || ratings.length == 0) return 0; int[] num = new int[ratings.length]; num[0] = 1;//at least has 1 candy for(int i = 1; i < ratings.length; i++) { if(ratings[i] > ratings[i - 1]) { //if child i has rating higher than i-1, which should 1 bigger than its left neighbour num[i] = num[i - 1] + 1; }else { num[i] = 1; } } int res = num[ratings.length - 1]; for(int i = ratings.length - 2; i >= 0; i--) { int cur = 1; if(ratings[i] > ratings[i + 1]) { //if child i has rating higher than its right neighbour, but the candies array did not //represented this situation correctly, then correct it. cur = num[i + 1] + 1; } res += Math.max(cur, num[i]); num[i] = cur; } return res; } }
No comments:
Post a Comment