python分糖果_[Leetcode] Candy 分糖果

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?

贪心法

复杂度

时间 O(N) 空间 O(N)

思路

典型的贪心法,如果一个孩子比另一个孩子的分高,我们只多给1块糖。我们可以先从左往右遍历,确保每个孩子根他左边的孩子相比,如果分高,则糖要多1个,如果分比左边低,就只给一颗。然后我们再从右往左遍历,确保每个孩子跟他右边的孩子相比,如果分高则糖至少多1个(这里至少多1个的意思是,我们要取当前孩子手里糖的数量,和其右边孩子糖的数量加1,两者的较大值)。

代码

public class Solution {

public int candy(int[] ratings) {

if(ratings.length <= 1){

return ratings.length;

}

int[] candies = new int[ratings.length];

candies[0] = 1;

// 先从左往右分糖,分数较高的多拿一颗糖,分数较少的只拿一颗糖

for(int i = 1; i < ratings.length; i++){

if(ratings[i] > ratings[i - 1]){

candies[i] = candies[i - 1] + 1;

} else {

candies[i] = 1;

}

}

int sum = candies[candies.length - 1];

// 再从右往左继续分糖,分数较高的确保比右边多一颗就行了

for(int i = ratings.length - 2; i >= 0; i--){

if(ratings[i] > ratings[i + 1]){

candies[i] = Math.max(candies[i + 1] + 1, candies[i]);

}

sum += candies[i];

}

return sum;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值