【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 <= 0) return 0;
        int[] dp = new int[ratings.length];
        dp[0] = 1;
        for (int i = 1; i < dp.length; i++) {
            if (ratings[i] > ratings[i - 1]) {
                dp[i] = dp[i - 1] + 1;
            } else {
                dp[i] = 1;
            }
        }
        int res = dp[dp.length - 1];
        for (int i = dp.length - 2; i >= 0; i--) {
            if (ratings[i] > ratings[i + 1]) {
                dp[i] = Math.max(dp[i + 1] + 1, dp[i]);
            }
            res += dp[i];
        }
        return res;
    }
}

执行耗时:3 ms,击败了66.08% 的Java用户
内存消耗:39.5 MB,击败了66.45% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值