LeetCode:Candy

Posted walker lee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Candy相关的知识,希望对你有一定的参考价值。

Candy




Total Accepted: 52308 Total Submissions: 231427 Difficulty: Hard

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?

Subscribe to see which companies asked this question

Hide Tags
 Greedy



















思路:

1.先给每个小孩分1 个candy;

2.从左往右:如果,左<右,则右边小孩加1颗candy;

2.从右往左:如果,左>右,则左边小孩要比右边的candy多。


java code:

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


以上是关于LeetCode:Candy的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] Candy Crush 糖果粉碎

微信小程序代码片段

VSCode自定义代码片段——CSS选择器

谷歌浏览器调试jsp 引入代码片段,如何调试代码片段中的js

片段和活动之间的核心区别是啥?哪些代码可以写成片段?

VSCode自定义代码片段——.vue文件的模板