首页 > 代码库 > [Leetcode] Candy
[Leetcode] Candy
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)。
1 public class Solution { 2 public int candy(int[] ratings) { 3 if(ratings.length==0) 4 return 0; 5 int N=ratings.length; 6 int[] candies=new int[N]; 7 candies[0]=1; 8 for(int i=1;i<N;++i){ 9 if(ratings[i]>ratings[i-1]){10 candies[i]=candies[i-1]+1;11 }else{12 candies[i]=1;13 }14 }15 for(int i=N-2;i>=0;--i){16 if(ratings[i]>ratings[i+1]&&candies[i]<=candies[i+1])17 candies[i]=candies[i+1]+1;18 }19 int result=0;20 for(int iCandy:candies){21 result+=iCandy;22 }23 return result;24 }25 }
[Leetcode] Candy
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。