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?

一刷
题解:
先从左到右,和左边的相比,如果大于左边,就比左边多给一根
再从右到左,和右边的相比,如果大于右边,就取当前值和右边+1的最大值。

public class Solution {
    public int candy(int[] ratings) {
        int len = ratings.length;
        if(len<=1) return len;
        int[] num = new int[len];
        Arrays.fill(num, 1);
        
        for(int i=1; i<len; i++){
            if(ratings[i] > ratings[i-1]) num[i] = num[i-1]+1;
        }
        
        for(int i=len-1; i>0; i--){
            if(ratings[i-1] > ratings[i])
                num[i-1] = Math.max(num[i] + 1, num[i-1]);
        }
        
        int result = 0;
        for(int i=0; i<len; i++) result += num[i];
        
        return result;
        
    }
}

二刷
先从左到右,如果比左边的大,比左边多给一根。
然后从右到左,如果i-1比右边的数i大,则give[i]+1和give[i-1]中取较大值

public class Solution {
    public int candy(int[] ratings) {
        int len = ratings.length;
        int total = 0;
        int[] give = new int[len];
        Arrays.fill(give, 1);
        for(int i=1; i<len; i++){
            if(ratings[i] > ratings[i-1]) give[i] = give[i-1]+1;
        }
        
        for(int i=len-1; i>0; i--){
            if(ratings[i-1] > ratings[i])  give[i-1] = Math.max(give[i]+1, give[i-1]);
        }
        
        int res = 0;
        for(int i=0; i<len; i++){
            res += give[i];
        }
        
        return res;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • There are N children standing in a line. Each child is as...
    ShutLove阅读 2,999评论 0 0
  • 问题分析 There are N children standing in a line. Each child ...
    codingXue阅读 1,292评论 0 0
  • There are N children standing in a line. Each child is as...
    juexin阅读 1,702评论 0 0
  • There are N children standing in a line. Each child is as...
    荔枝不吃阅读 1,589评论 0 0
  • 01 周末的这天准时地还是在这个点醒,这已经显然成为一个习惯,就像手机闹钟如果你定死了一个时间,它就会在那个点准时...
    黑发长衣阅读 1,634评论 0 2

友情链接更多精彩内容