Candy
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.
Test Instructions Analysis:
In fact, as long as there is no bigger than him, you can only divide 1. If the left and right is bigger than him, then one more points around. The result is the most provincial.
The difficulty lies in: for example, [5,4,3,2,4] know that 5 is bigger than the two sides, but how to judge exactly how deep it is (where the trough is) "should be a few more appropriate." If you have been struggling to figure this out, then go to a "dead end".
In fact, the description of the topic itself is a good solution: the initialization of each person's candy number is initialized to 1. Each traversal considers only the left and right side, that is, to traverse from the left, if I>i-1 is candy[i]=candy[i-1], and then iterate from right to left, if I>i+1 and Candy[i]<=candy[i+1] Cand[i]=candy [I+1]+1; Such a two-time traversal, the left and right sides are taken into account. Finally add candy[i] and sum it up.
Code:
Class solution{public
:
int Candy (vector<int> &ratings) {
int n=ratings.size ();
if (n==1) return 1;
int i,sum=0;
Vector<int> Candy (n,1); First set the value of each person to 1
//before scanning for
(i=1;i<n;i++) {
if (ratings[i]>ratings[i-1]) candy[i]=candy[i-1]+1;
}
Forward scan for
(i=n-2;i>=0;i--) {
if (ratings[i]>ratings[i+1] && candy[i]<=candy[i+1]) candy[i]=candy[i+1]+1;
}
for (i=0;i<n;i++)
sum+=candy[i];
return sum;
}
};