题目来源:leetcode
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.
思路:建立另一个数组存放当前应该存放的糖果数量,每当第id个小于前面的时候应该去更新往前更新
代码如下:通过率65%不知道为啥
class Solution {
public int candy(int[] ratings) {
int dp[]=new int[ratings.length];//记录每个位置的应该发的最少糖果数量
dp[0]=1;
int sum=0;
for(int i=1;i<dp.length;i++)
{ if(ratings[i]>ratings[i-1])
dp[i]=dp[i-1]+1;
else if(ratings[i]==ratings[i-1])
dp[i]=1;
else{
dp[i]=1;
//dp[i-1]=2;
if(dp[i-1]==1)
for(int j=i-1;j>=0;j--){
if(ratings[j]>ratings[j+1])
dp[j]=dp[j+1]+1;
else if(ratings[j]<ratings[j+1]) break;
// if(ratings[j]==ratings[j+1])
// dp[j]=dp[j+1];
}
}
}
for(int i=0;i<ratings.length;i++)
{sum+=dp[i];}
return sum;
}
}