• [leet code 135]candy


    1 题目

    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?

    2 思路

    按照网上的思路,每个孩子至少有一个糖果,先从左到右遍历一遍,写出递增的糖果数,再从右到左遍历一遍完成递减的糖果数。这种大小与左右两边数据相关的问题,均可以采用这个思路。另外,有另一种空间复杂度O(1),时间复杂度O(n)的思路,可以参考http://www.cnblogs.com/felixfang/p/3620086.html

    3 代码

     public int candy(int[] ratings) {  
            if(ratings == null || ratings.length == 0)  
            {  
                return 0;  
            }  
            int[] candyNums = new int[ratings.length];  
            candyNums[0] = 1;  
                 
            for(int i = 1; i < ratings.length; i++)  
            {  
                if(ratings[i] > ratings[i-1])  //如果第i个孩子比第i - 1孩子等级高,
                {  
                    candyNums[i] = candyNums[i-1]+1;  
                }  
                else //每人至少有一个糖果
                {  
                    candyNums[i] = 1;  
                }  
            }  
             
            for(int i = ratings.length-2; i >= 0; i--)  
            {  
                
                if(ratings[i] > ratings[i + 1] && candyNums[i] <= candyNums[ i + 1]) //如果第i个孩子比第i + 1孩子等级高并且糖果比i+1糖果少 
                {  
                     candyNums[i] = candyNums[i + 1] + 1;
                }    
            }  
            
            int total = 0;
            for (int i = 0; i < candyNums.length; i++) {
                total += candyNums[i];
            }
            
            return total;  
        }
  • 相关阅读:
    金刚经与心经之比较
    ECMWF 和 GFS 模型
    LSTM之父Jürgen Schmidhuber评图灵
    STM32相关知识点
    最全C++11/14/17/20/23 的新特性代码案例
    C++ 在线工具
    如何在 Proteus 中设计 PCB
    STM32电源框图解析
    【新特性速递】填一个坑
    【新特性速递】表格加载速度足足 3 倍提升,爱了爱了
  • 原文地址:https://www.cnblogs.com/lingtingvfengsheng/p/4304505.html
Copyright © 2020-2023  润新知