# 6 Candy_Leetcode

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?

Code:

class Solution {
public:
int candy(vector<int> &ratings) {
int n = ratings.size();
if(n == 0) return 0;
int sum = 0;

vector<int> left(n, 1);
vector<int> right(n, 1);

for(int i = 1; i < n; i++)
{
if(ratings[i] > ratings[i-1]) left[i] = left[i-1] + 1;
else left[i] = 1; // first error, when equal, no camparison, so the candy could start from 1
}

for(int j = n-2; j >= 0; j--)
{
if(ratings[j] > ratings[j+1]) right[j] = right[j+1] + 1;
else right[j] = 1;
}

for(int i = 0; i < n; i++) sum += max(left[i], right[i]);

return sum;
}
};


posted @ 2014-10-16 21:15  Avril  阅读(272)  评论(0编辑  收藏