Problem:
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?
Hide TagsGreedyTest instructions: Give sweets to small pots, high-quality candy to more
Thinking:
(1) A simple greedy question, why is the pass rate so low?? There is no mention in the title how to make candy when the property is equal. is not a serious problem again. Submit Discovery,
122 of the small pot friends sent 4 candies, the third small pot friends sent 1 sweets, in exchange for you are small pot friends, you will be happy ...
(2) Apart from the same situation, the problem should be handled as long as it is in the descending condition. Increment or disorderly order to deal with something.
Code
Class solution{Public:int Candy (vector<int> &ratings) {int total = 0; Total Candies int length = 0; Continuous descending length of rate int nprecancnt = 1; Previous Child ' s candy count int beforedenc = nprecancnt; if (ratings.begin () = Ratings.end ()) {total++;//counting the first child ' s candy (1). for (Vector<int>::iterator i = Ratings.begin () +1; i!= ratings.end (); i++) {if (*i < * (i-1)) {length++; if (beforedenc <= length) {total++; } Total + = length; nprecancnt = 1; This are important, it ensures that once we leave the decending sequence, candy number start from 1} else {int curcancnt = 0; if (*i > * (i-1)) {curcancnt = (nprecancnt + 1); } else {curcancnt = 1; } Total + = curcancnt; nprecancnt = curcancnt; length = 0; Reset length of decending sequence beforedenc = curcancnt; }}}, return total;};
Leetcode | | 135, Candy