Candy

来源:互联网 发布:阿里云网站日志在哪里 编辑:程序博客网 时间:2024/06/08 09:35

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?

因此根据题意,思路可以如下:

从左向右遍历,如果第i个孩子比第i-1孩子等级高,则dp[i]=dp[i-1]+1,否则为1

从右向左遍历,如果第i个孩子比第i+1孩子等级高并且糖果比i+1糖果少,则dp[i]=dp[i+1]+1

public int candy(int[] ratings) {int len=ratings.length;if(ratings==null||len<=0)return 0;int result=0;int[] dp=new int[len];dp[0]=1;for(int i=1;i<len;i++){if(ratings[i]>ratings[i-1])dp[i]=dp[i-1]+1;elsedp[i]=1;}result+=dp[len-1];for(int i=len-2;i>=0;i--){int cur=dp[i];if(ratings[i]>ratings[i+1])cur=dp[i+1]+1;result+=Math.max(cur,dp[i]);dp[i]=cur;}return result;}


0 0
原创粉丝点击