每日AC--LeetCode-Candy


每日AC--LeetCode-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?



之前看过网易有一个类似的,说是分奖金的, 就是所有人排成一排,分数高比左右两边分数高的,不能比他左右两边得到的奖金少


AC代码:



import java.util.Arrays;

/**
 * 类说明
 * 
 * <pre>
 * Modify Information:
 * Author        Date          Description
 * ============ =========== ============================
 * DELL          2017年9月8日    Create this file
 * </pre>
 * 
 */

public class LeetCodeCandy {

    public int candy(int[] ratings) {
        if(null == ratings || ratings.length ==0){
            return 0;
        }
        
        int sum = 0;

        // 高分的 要比他旁边的两个人得到的糖多
        int[] count = new int[ratings.length];
        //初始化为1 
        Arrays.fill(count, 1);
        
        //从左向右扫描一遍 初始化都是1 嘛 
        for(int i = 1; i < ratings.length; i++){
            if(ratings[i] > ratings[i-1]){
                count[i] = count[i-1]+1;
            }
        }
        
        // 经过前 一轮 从前向后扫描只满足了中间的比左边的大,现在要满足中间的比右边的大,需要从后向右扫描
        for(int i = ratings.length-1; i >=1; i--){
            if(ratings[i-1] > ratings[i] && count[i-1] <=count[i]){
                count[i-1] = count[i] +1;
            }
        }
        
        
        for(int i = 0; i <count.length; i++){
            sum +=count[i];
        }
        
        return sum ;
       
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int[] ratings = {1,3,4,0,5};
        int ans  = new LeetCodeCandy().candy(ratings);
        System.out.println(ans);
    }

}








wangxiaoming CSDN认证博客专家 架构 Spring Boot Redis
博客是很好的总结和记录工具,如果有问题,来不及回复,关注微信公众号:程序员开发者社区,获取我的联系方式,向我提问,也可以给我发送邮件,联系 1275801617@qq.com
©️2020 CSDN 皮肤主题: Age of Ai 设计师: meimeiellie 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值