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

    public class Solution {
        public int candy(int[] ratings) {
            /*其实只要左右不比他大,就可以只分1个。如果左右比他大,左右就多分一个。这样的结果就是最省的。
            
            其实题目的描述本身就是一个很好的方案:初始化将每个人的糖果数都初始化为1。每次遍历只考虑左右一边,
            即从左向右遍历,如果i>i-1 则  candy[i]=candy[i-1]+1;再从右向左遍历一次,如果i>i+1 并且 candy[i]<=candy[i+1](注意!!) 
            则 cand[i]=candy[i+1]+1; 这样的两次遍历,左右两边都顾及到了。最后将candy[i]相加求和就好了。
            每一边只考虑递增序列!!!*/
            if(ratings==null||ratings.length<1) return 0;
            int len=ratings.length;
            int candy[]=new int[len];
            int res=0;
            for(int i=0;i<len;i++){
                candy[i]=1;
            }
            for(int i=1;i<len;i++){
                if(ratings[i-1]<ratings[i]){
                    candy[i]=candy[i-1]+1;
                }
                
            }
            for(int i=len-2;i>=0;i--){
                if(ratings[i+1]<ratings[i]&&candy[i]<=candy[i+1]){////
                    candy[i]=candy[i+1]+1;
                }
            }
            for(int i=0;i<len;i++){
                res+=candy[i];
            }
            return res;
            
        }
    }
  • 相关阅读:
    多条件查询
    BootStrap——BootStrap练习(栅格系统、组件、插件)
    BootStrap——栅格系统
    BootStrap——BootStrap插件
    BootStrap——BootStrap组件
    BootStrap——按钮、图片
    BootStrap——CSS
    BootStrap——新建BootStrap项目
    JQ——表单验证插件(validation)
    JQ——事件(表单、文档/窗口)
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4678120.html
Copyright © 2011-2022 走看看