您的位置:首页 > 职场人生

117_leetcode_Candy

2014-06-25 09:37 363 查看
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?

1:特殊情况;2:从前到后扫描数组,根据前后相邻rating值来确定饼干的数量;3:从后到前扫描数组,根据后前之间的关心调整饼干的数量;4:注意边界点;4:最后统计所有饼干数量

int candy(vector<int> &ratings)
{
int size = (int)ratings.size();
if(size <= 1)
{
return size;
}

vector<int> result(size, 0);
result[0] = 1;

//从左到右扫描数组
for(int i = 1; i < size; i++)
{
if(ratings[i] > ratings[i-1])
{
result[i] = result[i-1] + 1;
}
else
{
result[i] = 1;
}
}

//从右到左扫描数组
for(int i = size - 2; i >= 0; i--)
{
if(ratings[i] > ratings[i+1])
{
result[i] = (result[i] > 1 + result[i+1] ? result[i] : 1 + result[i+1]);
}
}

int maxValue = 0;
for(int i = 0; i < size; i++)
{
maxValue += result[i];
}

return maxValue;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息