Candy Java

来源:互联网 发布:淘宝猪哼少是正品澄清 编辑:程序博客网 时间:2024/04/30 00:51

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?

Have you been asked this question in an interview?

Key to Solve: DP 
same idea as Trapping Rain Water Java
    1.Scan from left -> right =>
    make sure left-hand side with higher rate has more candy than their neighbors

    2.Scan from right -> left =>
    make sure left-hand side Child with higher rate has more candy than their neighbors

    3. As a result, each children has # of candy they deserve

Check the coding in detail below
public class Solution {    public int candy(int[] ratings) {         if(ratings.length==0) return 0;        int len=ratings.length;        int total=0;        int[] candyNum=new int[len];        candyNum[0]=1;        //from left -> right        //make sure right-hand side Child with higher rate        //has more candy than their neighbors        for(int i=1;i<len;i++){            candyNum[i]=1;            if(ratings[i]>ratings[i-1]){                candyNum[i]=candyNum[i-1]+1;            }        }        //from right -> left        //make sure left-hand side Child with higher rate        // has more candy than their neighbors        total=candyNum[len-1];        for(int i=len-2;i>=0;i--){            if(ratings[i]>ratings[i+1]){                candyNum[i]=Math.max(candyNum[i],candyNum[i+1]+1);            }            total+=candyNum[i];        }        return total;    }}



   
0 0
原创粉丝点击