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

    详见:https://leetcode.com/problems/candy/description/

    Java实现:

    首先初始化每个人一个糖果,然后遍历两遍,第一遍从左向右遍历,如果右边小盆友的等级高,右边小盆友加一个糖果,这样保证了一个方向上高等级的糖果多。然后再从右向左遍历一遍,如果相邻两个左边的等级高,而左边的糖果又少的话,则左边糖果数为右边糖果数加一。最后再把所有小盆友的糖果数都加起来返回即可。

    class Solution {
        public int candy(int[] ratings) {
            int n=ratings.length;
            if(n==0||ratings==null){
                return 0;
            }
            int[] dp=new int[n];
            Arrays.fill(dp,1);
            int candy=0;
            for(int i=1;i<n;++i){
                if(ratings[i]>ratings[i-1]){
                    dp[i]=dp[i-1]+1;
                }
            }
            for(int i=n-2;i>=0;--i){
                if(ratings[i]>ratings[i+1]){
                    dp[i]=Math.max(dp[i],dp[i+1]+1);
                }
            }
            for(int val:dp){
                candy+=val;
            }
            return candy;
        }
    }

    参考:https://www.cnblogs.com/grandyang/p/4575026.html

  • 相关阅读:
    数据库完整性约束
    系统介绍
    全栈性能测试修炼宝典--Jmeter实战(一)
    数据驱动(四)
    数据驱动(五)
    数据驱动(三)
    数据驱动(二)
    数据驱动(一)
    Robot Framework 三种测试用例模式
    sublime text---注释
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8724631.html
Copyright © 2011-2022 走看看