leetcode 135. Candy 三种解法

一道关于分糖果的LeetCode问题,要求根据孩子的评分公平分配糖果,使得评分高的孩子得到更多糖果。文章介绍了三种解法:一次遍历、排序后的贪心解法和两次遍历的高效方法,重点讨论了贪心策略在解决此类问题中的应用。
摘要由CSDN通过智能技术生成

题意

给每个孩子分糖果,如果这个孩子的rating比相邻的孩子高,那么他分到的糖果就要比他多,求最少需要多少糖果。

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?

Example 1:

Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
             The third child gets 1 candy because it satisfies the above two conditions.

test cases

[3,2,1,1,2,4,3,2,1,0,0]
[1,0,2]
[1,0,2,2,3,4,5,6,7,7,8,9,0,1,2,3,2,1,1,2,1,0]
[3,2,1,1,2,3,2,2,3,4,2,2,1]
[]
[1,2,2,2,1,1,3,1,2,10,20,19,18,17,16,15,4,3,2,1,2,2,1,1,0,1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1,0,10]
[1]
[0]

解1 只遍历一遍即得出结果

时间复杂度O(N)

[3,2,1,1,2,4,3,2,1,0,0]对这个用例,分法应该为:

[3,2,1,1,2,5,4,3,2,1,1]

过程为:

[1]

[2,1]

[3,2,1]

[3,2,1,1]

[3,2,1,1,2]

[3,2,1,1,2,3]

[3,2,1,1,2,3,1]

[3,2,1,1,2,3,2,1]

[3,2,1,1,2,4,3,2,1]

[3,2,1,1,2,5,4,3,2,1]

[3,2,1,1,2,5,4,3,2,1,1]

思路:维护3个变量:当前高度、前最大高度、当前台阶高度。

如果比前一个孩子分高,

​ 如果是第一次上升,那么当前台阶高度=2,

​ 如果不是第一次上升,那么当前台阶高度++;

​ 结果加上当前台阶高度。

如果比前一个孩子分低,

​ 如果不是第一次下降,那么台阶高度++;

​ 如果是第一次下降,那么台阶高度=1;

​ 结果加上 high < maxHigh ? high : maxHigh + 1;

如果相等,

​ 与前面隔断。

讲不清楚,也很复杂,直接上代码

    // Runtime: 2 ms, faster than 95.29% of Java online submissions for Candy.
    //Memory Usage: 39.7 MB, less than 16.42% of Java online submissions for Candy.
    public int candy(int[] ratings) {
   
        if (ratings == null || ratings.length == 0)
            return 0;
        int prev = ratings[0];
        int sum = 1;
        int level = 1;
        int high = 1;
        int maxHigh = 1;
        for (int i = 1; i < ratings.length; i++) {
   
            if (ratings
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值