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
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- candy
- Candy
- Candy
- Candy
- Candy
- Swift学习笔记之数组(三)
- Cmake使用教程
- 递归函数时间复杂度分析
- MATLAB out of memory深层次解决办法
- 循环获取所有控件
- Candy
- UVA 348 Optimal Array Multiplication Sequence(最优矩阵链乘)
- Product of Array Except Self
- Qt 操作系统环境变量
- JVM垃圾回收
- 浅谈Android中的基础动画(图文详解)
- 背单词App开发日记6(终章总结)
- A1070. Mooncake (25)
- OC中继承代理委托类别