LeetCode力扣之135. 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?

package leetCode;

import java.util.Arrays;

/**
 * Created by lxw, liwei4939@126.com on 2018/3/27.
 */
public class L135_Candy {

    /*从左到右遍历一次,再从右到左遍历一次,具体地,
    * 从左到右遍历,使得右边评分更高的元素比左边至少多于1个糖果
    * 从右到左遍历,使得左边评分更高的元素比右边至少多于1个糖果
    * */
    public int candy(int[] ratings){
        int[] candies = new int[ratings.length];
        Arrays.fill(candies, 1);

        for (int i = 1; i < candies.length; i++){
            if (ratings[i] > ratings[i-1]){
                candies[i] = candies[i-1] + 1;
            }
        }

        for (int i = candies.length-2; i >= 0; i--){
            if (ratings[i] > ratings[i+1]){
                candies[i] = Math.max(candies[i],candies[i+1] +1);
            }
        }

        int sum = 0;
        for (int candy : candies){
            sum += candy;
        }
        return sum;
    }

    
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值