【LeetCode】135. Candy 分发糖果(Hard)(JAVA)

【LeetCode】135. Candy 分发糖果(Hard)(JAVA)

题目地址: https://leetcode.com/problems/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?

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.

题目大意

老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。

你需要按照以下要求,帮助老师给这些孩子分发糖果:

  • 每个孩子至少分配到 1 个糖果。
  • 相邻的孩子中,评分高的孩子必须获得更多的糖果。

那么这样下来,老师至少需要准备多少颗糖果呢?

解题方法

  1. 遍历两次,一次从左到右,一次从右到左,结果保存到一个一维数组里
  2. 先从左到右,如果当前元素大于前面的元素,前一个的结果 + 1,min[i] = min[i - 1] + 1
  3. 然后从右到左,如果当前元素大于前面的元素,前一个的结果 + 1, min[i + 1] + 1,然后和从左到右遍历的结果比较,取大的值
class Solution {
    public int candy(int[] ratings) {
        if (ratings.length <= 1) return ratings.length;
        int[] min = new int[ratings.length];
        for (int i = 0; i < ratings.length; i++) {
            if (i == 0) {
                min[i] = 1;
            } else if (ratings[i] > ratings[i - 1]) {
                min[i] = min[i - 1] + 1;
            } else {
                min[i] = 1;
            }
        }
        int res = 0;
        for (int i = ratings.length - 1; i >= 0; i--) {
            if (i < ratings.length - 1 && ratings[i] > ratings[i + 1]) {
                min[i] = Math.max(min[i], min[i + 1] + 1);
            }
            res += min[i];
        }
        return res;
    }
}

执行耗时:3 ms,击败了77.77% 的Java用户
内存消耗:39.1 MB,击败了97.70% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值