There is N children standing in a line. Each child is assigned a rating value. You is giving candies to these children subjected to the following Requirements:each child must has at least one candy. Children with a higher rating get more candies than their neighbors. What's the minimum candies you must give?
A wrong way is, the children's rating value from small to large sort, according to the order of the number of candy, the number of small, hair candy is also less, large number, hair candy, if the next two serial number of the rating, hair candy should also be the same. The code is as follows:
int Candy (vector<int> &ratings) {
vector<int> idx;
Idx.push_back (0);
Sort the ratings and obtain the sorted indices for
(int i=1; i<ratings.size (); i++)
{
int J;
int tmp = ratings[i];
Idx.push_back (i);
for (j=i-1; j>=0; j--)
{
if (ratings[j]>tmp)
idx[j+1] = idx[j];
}
IDX[J+1] = i;
}
int candynum = 0; The number of candies given to the current child
int totalcandynum = 0;//total number of candies for
(int i= 0; I<ratings.size (); i++)
{
if (i==0)
{
candynum = 1;//1 Candy is given to the first child
}
if (i>0)
if (Ratings[idx[i]]>ratings[idx[i-1]])
Candynum + = 1; Only if rating is bigger would he/she be given 1 one candy
totalcandynum + = Candynum;
}
return totalcandynum;
}
The failure case of the above method is ratings = {3,2,3,1}. According to the above method, the 2nd child gets the candy is 2, but actually gives him 1 to be OK.
Here's the correct solution:
Scan the rating array from left to right and then from right to left. In every scan just consider the rising order (L->r:r[i]>r[i-1] or r->l:r[i]>r[i+1]), assign +1 candies to th E rising position.
The final candy array is the maximum (max (right[i],left[i)) and each position.
The total candies is the sum of the final candy array.
Code:
Class Solution {public
:
int GetC (vector<int> &r) {
vector<int> lc (R.size (), 1);
Vector<int> RC (R.size (), 1);
int res=0;
for (int i=1;i<lc.size (); i++) {
if (R[i]>r[i-1]) {
lc[i]=lc[i-1]+1;
}
}
for (int i=rc.size () -2;i>=0;i--) {
if (r[i]>r[i+1]) {
rc[i]=rc[i+1]+1;
}
}
for (int i=0;i<r.size (); i++) {
Res+=max (lc[i],rc[i]);
}
return res;
}
int Candy (vector<int> &ratings) {
return GetC (ratings);
}
};