Leetcode Candy
2017-07-17 11:18
357 查看
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?
因为至少有一个糖果,初始时将candy数组赋值为1.因为高rating的children要比neighbors获得更多的糖果。所以先进行一次遍历,高rating的children的糖果数比前一个children 多1.但这样处理完,还存在一种不符合情况的没有处理。前一个children的糖果数为1,而后一个rating更低的children糖果数也为1,这样是不符合题目要求的。因此从尾到头开始遍历,如果前一个children的rating大于后一个children,则设置其糖果数为max(candy[i],candy[i+1])
,这样就修正了该情况,同时也会因为该修改而修改其他children的糖果数,从而符合题目要求。
代码如下:
class Solution {
public:
int candy(vector<int>& ratings) {
int num = ratings.size();
int candy[num],total=0;;
for(int i=0;i<num;i++)
candy[i] = 1;
for(int i=1;i<num;i++)
{
if(ratings[i] > ratings[i-1])
candy[i] = candy[i-1]+1;
}
total = candy[num-1];
for(int i=num-2;i>=0;i--)
{
if(ratings[i] > ratings[i+1])
{
candy[i] = max(candy[i],candy[i+1]+1);
}
total += candy[i];
}
return total;
}
};
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?
因为至少有一个糖果,初始时将candy数组赋值为1.因为高rating的children要比neighbors获得更多的糖果。所以先进行一次遍历,高rating的children的糖果数比前一个children 多1.但这样处理完,还存在一种不符合情况的没有处理。前一个children的糖果数为1,而后一个rating更低的children糖果数也为1,这样是不符合题目要求的。因此从尾到头开始遍历,如果前一个children的rating大于后一个children,则设置其糖果数为max(candy[i],candy[i+1])
,这样就修正了该情况,同时也会因为该修改而修改其他children的糖果数,从而符合题目要求。
代码如下:
class Solution {
public:
int candy(vector<int>& ratings) {
int num = ratings.size();
int candy[num],total=0;;
for(int i=0;i<num;i++)
candy[i] = 1;
for(int i=1;i<num;i++)
{
if(ratings[i] > ratings[i-1])
candy[i] = candy[i-1]+1;
}
total = candy[num-1];
for(int i=num-2;i>=0;i--)
{
if(ratings[i] > ratings[i+1])
{
candy[i] = max(candy[i],candy[i+1]+1);
}
total += candy[i];
}
return total;
}
};
相关文章推荐
- LeetCode: Candy
- Candy [leetcode] O(n)时间复杂度,O(1)空间复杂度的方法
- LeetCode -- Candy
- Candy:对样例存在困惑的一道leetcode
- leetcode -- Candy -- 重点
- [LeetCode]Candy 递归
- Candy--LeetCode
- LeetCode candy
- LeetCode :: Candy
- 【LeetCode】Candy 解题报告
- LeetCode || Candy
- LeetCode Candy
- Leetcode135 candy
- leetcode 135 —— Candy
- [leetcode-135]Candy(java)
- 【leetcode】Candy(python)
- LeetCode Candy
- LeetCode2.1.22 (Candy)
- leetcode: Candy
- Candy -- leetcode