leetcode之candy
2017-08-13 21:12
253 查看
题目:
There are N children standing ina line. Each child is assigned a rating value.
You are giving candies to these childrensubjected to the following requirements:
Each child musthave at least one candy.
Children with ahigher rating get more candies than their neighbors.
What is the minimum candies you must give?
思路:
用一个数组 candy
,表示第i
个小孩所应该发的最少糖果数。
数组 ratings
表示每个小孩的评分。
1. 从左到右扫描一遍,
candy[i] = 1,
if ratings[i] <= ratings[i-1] ;
candy[i] = candy[i-1] + 1,
if ratings[i] > ratings[i-1]
2. 从右到左扫描一遍,
candy[i] = candy[i],
if ratings[i] <= ratings[i+1] ;
candy[i] = max(candy[i], candy[i+1] + 1),
if ratings[i] > ratings[i+1]
解法:
动态规划
复杂度:
时间:时间 O(n),空间
O(n)
实现:
public int candy(int[] ratings){
intsize=ratings.length;
if(size<=1)return size;
int[]nums=new int[size];
for(inti=0;i<size;i++){
nums[i]=1;
}
for(intj=1;j<size;j++){
if(ratings[j]>ratings[j-1])nums[j]=nums[j-1]+1;
}
for(intm=size-1;m>0;m--){
if(ratings[m-1]>ratings[m]){
nums[m-1]=Math.max(nums[m]+1,nums[m-1]);
}
}
intresult=0;
for(intn=0;n<size;n++){
result+=nums
;
}
returnresult;
}
There are N children standing ina line. Each child is assigned a rating value.
You are giving candies to these childrensubjected to the following requirements:
Each child musthave at least one candy.
Children with ahigher rating get more candies than their neighbors.
What is the minimum candies you must give?
思路:
用一个数组 candy
,表示第i
个小孩所应该发的最少糖果数。
数组 ratings
表示每个小孩的评分。
1. 从左到右扫描一遍,
candy[i] = 1,
if ratings[i] <= ratings[i-1] ;
candy[i] = candy[i-1] + 1,
if ratings[i] > ratings[i-1]
2. 从右到左扫描一遍,
candy[i] = candy[i],
if ratings[i] <= ratings[i+1] ;
candy[i] = max(candy[i], candy[i+1] + 1),
if ratings[i] > ratings[i+1]
解法:
动态规划
复杂度:
时间:时间 O(n),空间
O(n)
实现:
public int candy(int[] ratings){
intsize=ratings.length;
if(size<=1)return size;
int[]nums=new int[size];
for(inti=0;i<size;i++){
nums[i]=1;
}
for(intj=1;j<size;j++){
if(ratings[j]>ratings[j-1])nums[j]=nums[j-1]+1;
}
for(intm=size-1;m>0;m--){
if(ratings[m-1]>ratings[m]){
nums[m-1]=Math.max(nums[m]+1,nums[m-1]);
}
}
intresult=0;
for(intn=0;n<size;n++){
result+=nums
;
}
returnresult;
}
相关文章推荐
- [LeetCode] Candy (分糖果),时间复杂度O(n),空间复杂度为O(1),且只需遍历一次的实现
- leetcode candy
- LeetCode: Candy
- LeetCode: Candy
- [LeetCode] Candy
- [Leetcode] Candy
- leetcode Candy
- leetcode 138: Candy (incompleted)
- [LeetCode] Candy (分糖果),时间复杂度O(n),空间复杂度为O(1),且只需遍历一次的实现
- leetcode[135] Candy
- [LeetCode] Candy
- leetcode -day9 Candy & Gas Station & Binary Tree Maximum Path Sum
- leetcode第16题(candy)
- Candy [leetcode]
- Candy leetcode java
- leetCode_Candy
- LeetCode-Candy
- [leetcode]Candy
- LeetCode135 Candy
- leetcode :Candy