• [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;
            
        }
    }
  • 相关阅读:
    luogu P2852 [USACO06DEC]Milk Patterns G
    FZOJ 4267 树上统计
    CF1303G Sum of Prefix Sums
    luogu P5311 [Ynoi2011]成都七中
    luogu P5306 [COCI2019] Transport
    SP34096 DIVCNTK
    luogu P5325 【模板】Min_25筛
    luogu P1742 最小圆覆盖
    求两直线交点坐标
    1098: 复合函数求值(函数专题)
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4678120.html
Copyright © 2020-2023  润新知