135. Candy 考验逻辑能力的时候到了
2017-01-02 14:20
246 查看
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?
int candy(vector<int>& ratings) {
int len = ratings.size(), res = 0, i;
if (len>0)
{
vector<int> number(len, 0); // to save the number of candies for child[0:N-1]
number[0] = 1;
// forward scan to calculate how many candies needed for child i to make sure it has more candies than
//its left neighbor if it has a higher rate, otherwise, give one candy to it
for (i = 1; i<len; ++i) number[i] = ratings[i]>ratings[i - 1] ? number[i - 1] + 1 : 1;
// backward scan to calculate to make sure child i has more candies than its right neighbor if it has
//a higher rate, pick the bigger one from forward and backward scans as the final number for child i
for (i = len - 2, res = number[len - 1]; i >= 0; --i)
{
if ((ratings[i]>ratings[i + 1]) && number[i]<(number[i + 1] + 1)) number[i] = number[i + 1] + 1;
res += number[i];
}
}
return res;
}
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?
int candy(vector<int>& ratings) {
int len = ratings.size(), res = 0, i;
if (len>0)
{
vector<int> number(len, 0); // to save the number of candies for child[0:N-1]
number[0] = 1;
// forward scan to calculate how many candies needed for child i to make sure it has more candies than
//its left neighbor if it has a higher rate, otherwise, give one candy to it
for (i = 1; i<len; ++i) number[i] = ratings[i]>ratings[i - 1] ? number[i - 1] + 1 : 1;
// backward scan to calculate to make sure child i has more candies than its right neighbor if it has
//a higher rate, pick the bigger one from forward and backward scans as the final number for child i
for (i = len - 2, res = number[len - 1]; i >= 0; --i)
{
if ((ratings[i]>ratings[i + 1]) && number[i]<(number[i + 1] + 1)) number[i] = number[i + 1] + 1;
res += number[i];
}
}
return res;
}
相关文章推荐
- Java笔记之 逻辑代码片段(从事职业之初所写有兴趣可以看看,提高初学者的代码能力)
- 惭愧,WS的时候Tomcat竟然出问题,而且自己没能力解决
- Hadoop运行的job作业的时候有具体十个步骤(能力工场--整理)
- 逻辑是生物在进行思考的时候,用来在所思考的事物与事物之间进行联系的方法
- 当你「ping 一下」的时候,你知道它背后的逻辑吗? – 运维派
- BM经典面试题:挑战你的逻辑分析能力(病狗问题)
- 运维同行在面试时候的心态和表达能力~~~
- 赚大钱的逻辑: 那些说靠能力的人都醒醒
- 调试的时候 才会走某些逻辑
- Hadoop运行的job作业的时候有具体十个步骤(能力工场--整理)
- 几道逻辑题(考你的逻辑推理能力)
- [置顶] 【逻辑思考】我们要有把坏事看成好事的能力
- 网盟推广考验百度销售能力
- 职场逻辑能力提升
- 数据在SQLLDR的时候提示错误,在逻辑记录结束之前未找到列(使用 TRAILING NULLCOLS)
- How do you make an awesome team?(来考验一下自己的英语能力吧)
- 正确的思考能力之一自省和逻辑推理-
- 网盟推广考验百度销售能力
- 如何提高逻辑推理能力和临时应变能力
- EditText 当设置为action为搜索的时候,设置点击了搜索以后直接搜索的逻辑