[LeetCode] 135. candy
来源:互联网 发布:淘宝客服自动回复大全 编辑:程序博客网 时间:2024/06/13 21:41
难度等级:hard
题目:
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?
题意:
有N个孩子站成一排。每个孩子都分配了一个等级值。 你把糖果给这些孩子受到以下要求:
- 每个孩子都必须至少有一个糖果。
- 具有较高等级值的孩子们比他左右小伙伴获得更多糖果。
题解:
可以用动态规划的方法解决,申请一个大小为N的数组dp[N-1];初始化为1,dp[i]的含义为第i个小孩在满足要求的情况下所获得的最少糖果数。dp[i]的计算过程如下:
1. 从前向后扫描,如果ratings[i]>ratings[i-1],那么dp[i]=dp[i-1]+1;
2. 从后向前扫描,如果ratings[i]>ratings[i+1]并且dp[i]<=dp[i-1],那么dp[i]=dp[i+1]+1;
因为dp[i]是每个小孩的最少糖果数,总的糖果数就是把所有的加起来即可。
代码:
class Solution {
public:
int candy(vector<int> &ratings) {
int n=ratings.size();
if(n==1)
return 1;
int dp[n];//第i个孩子的最少糖果数
int res=0;
for(int i=0;i<n;i++)
dp[i]=1;
for(int i=1;i<n;i++){
if(ratings[i]>ratings[i-1])
dp[i]=dp[i-1]+1;
}
for(int i=n-2;i>=0;i--){
if(ratings[i]>ratings[i+1]&&dp[i]<=dp[i+1])
dp[i]=dp[i+1]+1;
}
for(int i=0;i<n;i++)
res+=dp[i];
return res;
}
};
- [LeetCode]135.Candy
- 135. Candy Leetcode Python
- [Leetcode] 135. Candy
- [leetcode] 135.Candy
- [leetcode] 135. Candy
- leetcode 135. Candy
- leetcode 135. Candy
- [LeetCode]135. Candy
- LeetCode 135. Candy
- Leetcode 135. Candy
- leetcode.135. Candy
- LeetCode 135. Candy
- [leetcode] 【数组】 135. Candy
- LeetCode-135.Candy
- LeetCode 135. Candy
- Leetcode 135. Candy
- leetcode-135. Candy
- [LeetCode] 135. Candy
- C#简单写日志
- javaRunTime
- MongoDB的基本操作命令
- 会员导入存储过程
- 技术人员如何创业《一》—— 产品及想法
- [LeetCode] 135. candy
- Android 混淆提示 java.io.FileNotFoundException: ...\proguard-rules\release\aapt_rules.txt (系统找不到指定的路径)
- vue.js的学习之路
- NHibernate从入门到精通系列(1)——NHibernate概括
- 14二分查找
- 技术人员如何创业《二》- 合伙人的模式
- 【数据结构】二叉树的学习
- 正确理解SOA、SaaS和云计算之间的关系
- Unity中使用GL在Camera上绘制文字