您的位置:首页 > 其它

Candy - LeetCode

2014-01-23 06:50 295 查看
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,从前往后扫描,如果第i个小孩等级比第i-1个高,那么i的糖数目等于i-1的糖数目+1;从后往前扫描,如果第i个的小孩的等级比i+1个小孩高,但是糖的数目却小或者相等,那么i的糖数目等于i+1的糖数目+1。

该算法时间复杂度为O(N)

算法代码如下:

class Solution {
public:
int candy(vector<int> &ratings)
{
// Note: The Solution object is instantiated only once and is reused by each test case.
int *candyNum = new int[ratings.size()];//每个小孩的糖数目
for(int i = 0; i < ratings.size(); i++)
candyNum[i] = 1;
for(int i = 1; i < ratings.size(); i++)
if(ratings[i] > ratings[i-1])
candyNum[i] = candyNum[i-1] + 1;
for(int i = ratings.size()-2; i>=0; i--)
if(ratings[i] > ratings[i+1] && candyNum[i] <= candyNum[i+1])
candyNum[i] = candyNum[i+1] + 1;
int result = 0;
for(int i = 0; i < ratings.size(); i++)
result += candyNum[i];
delete []candyNum;
return result;
}
};


出处: http://www.cnblogs.com/TenosDoIt/p/3389479.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode