# [Leetcode] Candy (min Candy), Time complexity O (n), Spatial complexity O (1), and only one-time traversal implementation

Source: Internet
Author: User

[Leetcode] Candy (min Candy), Time complexity O (n), Spatial complexity O (1), and only one-time traversal implementation

Original question:

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?

Solution (1)

This problem itself can be done by greedy method, we use candy[n] to indicate the number of sweets per child, traversing the process, if the child i+1 rate is greater than the child I rate, then the best choice of the present nature is: give the child i+1 candy number = give children I candy number +1

If the child i+1 rate is less than equal to the child I rate of the whole? This is not a good time, because we do not know the best choice is to give children i+1 how much candy.

The workaround is to not handle this situation for the time being. Once the array has been traversed, we iterate over the array from the end of the head, and this back is greedy, so we can deal with the child who skipped it.

The last cumulative Candy[n] is to get the minimum number of sweets.

This solution requires O (n) of the auxiliary space to candy[].

Is there a better way?

Solution (2) This method and the code section refer to themethod of Shangrila.

Think back: Why do we need auxiliary space? When the rate of a child is a non-descending curve, we do not need auxiliary space, such as the rate of 5 children is 1,2,5,7,10. Then the number of sweets is naturally 1,2,3,4,5. And if the rate of 5 children is 1,2,5,5,10, then the number of sweets is naturally 1,2,3,1,2.

So if rate is a non-descending sequence, we can calculate exactly how many candies the child should give, and add the number of candies to the total.

What if your child's rate is declining? Can you handle it without the auxiliary space?

Suppose the rate of 5 children is 1,5,4,3,2. We calculate: When walking, the first child still candy is 1, the second child candy is 2, the third child candy to a few? We walk to the back to know that the second child gave too little candy, should give 4. Is there any way to calculate a correction value when traversing to the back so that the total number of candies is still correct by adding this modifier?

In fact, this correction is not difficult to calculate, because you can find the length of the descending sequence determines the second child should give a few sweets . Careful observation: Walking to the fourth child we know that the second child should not give 2, should give 3, so total to +=1; we know that the second child should not give 3 to 4, so total has to + = 1. Let's set a variable Beforedenc that represents the candy value given to the child before it enters the descending sequence, and then sets the length to express the current descending sequence. These two variables can determine whether total is to fix: When traversing the third child Beforedenc = 2, after each child traversal, because length has exceeded the beforedenc, each time total will be an extra +1 to fix the second child's candy number.

For the next three children, we can calculate this: traverse to the third child, because this is the second number of descending series, we total + = 1, the fourth child is the third number of descending series, the Total + = 2, and the fifth child is the fourth number of descending series, Total + = 3.

you can see that the total number of candies for the last three children is still correct , although the number of candies added by total each time is exactly the inverse of the number of candies the child is getting.

This method of edge-traversing edge correction guarantees a traversal and does not require an O (n) space to calculate the correct value of total.

Code:

`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] Candy (min Candy), Time complexity O (n), Spatial complexity O (1), and only one-time traversal implementation

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.