zoukankan      html  css  js  c++  java
  • 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?

    有N个孩子站在一条线。分配给每个孩子一个评级的价值。

    你把糖果给这些孩子受到以下需求:

    每个孩子必须至少有一个糖果。

    评级较高的孩子得到更多的糖果比他们的邻居。

    什么是你必须给的最低糖果吗?

    以上内容是用有道翻译进行翻译

    解题思路:------------------------------------------

    每个小孩先发一块糖,然后从左向右进行遍历,如果arr[i]>arr[i-1],就在前一个人的糖的数目的基础上加1;

    最后从右往左遍历,加上所有的糖(从右往左遍历是考虑到权值为:7 5 8 9 6 4 12)的情况

     

    import java.util.*;
    public class Solution {
        public int candy(int[] ratings) {
            if(ratings==null || ratings.length==0) {
                return 0;
            }
             
            int[] count = new int[ratings.length];
            //每个孩子初始都有一个糖果
            Arrays.fill(count,1);
            int sum = 0;
            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>0;i--) {
                sum+=count[i];
                if(ratings[i]<ratings[i-1] && count[i]>=count[i-1]) {
                    count[i-1] = count[i]+1;
                }
            }
            sum+=count[0];
             
            return sum;
        }
    }
  • 相关阅读:
    weex入门篇
    vue项目修改favicon
    IE9 下面, XMLHttpRequest 是不支持跨域请求的解决方法
    angularJS指令动态加载template
    angularJS的ng-repeat-start
    angular指令的详细讲解,不断补充
    实现输入框换行
    vue2.0实现一个模态弹框,内容自定义(使用slot)
    centos7 vnc 无法systemctl启动
    CentOS6.5配置rsyslog
  • 原文地址:https://www.cnblogs.com/googlemeoften/p/5826620.html
Copyright © 2011-2022 走看看