[LeetCode][Java]Candy@LeetCode

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?

Runtime: 392 ms

这道题跟Leetcode 一道contain water的题很像,思想很简单,可以把每个小朋友单独考虑,看下每个小朋友左边有紧邻的小朋友rate降序的个数,再看下该小朋友右边紧邻的小朋友降序的个数,然后就能确定本小朋友的最小“高度”(两降序个数中较大值),即为小朋友应得的糖果。

方法:从前往后,从后往前扫描两遍,并用lowleft[],lowright[]分别记录每个小朋友两边的降序个数即可~

public class Solution {

    public int candy(int[] ratings) {

        if(ratings.length==0) return 0;

        if(ratings.length==1) return 1;

        int[] lowleft=new int[ratings.length];

        int[] lowleft=new int[ratings.length];

        int ret=0;

        lowleft[0]=0;

        for(int i=1;i<ratings.length;i++){

            if(ratings[i-1]<ratings[i]) lowleft[i]=lowleft[i-1]+1;

            //else if(ratings[i-1]==ratings[i]) lowleft[i]=lowleft[i-1];

            else lowleft[i]=0;

        }

        lowright[ratings.length-1]=0;

        for(int j=ratings.length-2;j>=0;j--){

            if(ratings[j+1]<ratings[j]) lowright[j]=lowright[j+1]+1;

            //else if(ratings[j+1]==ratings[j]) lowright[j]=lowleft[j+1];

            else lowright[j]=0;

        }

        for(int i=0;i<ratings.length;i++){

            ret=ret+1+Math.max(lowright[i],lowleft[i]);

        }

        return ret;

    }

}

[LeetCode][Java]Candy@LeetCode,布布扣,bubuko.com

[LeetCode][Java]Candy@LeetCode

上一篇:java实现——007用两个栈实现队列


下一篇:改变Eclipse中java编译器版本出现错误:Java compiler level does not match the version of the installed Java project facet.