## 135. Candy

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?

b'
\n\n

## Solution

\n
\n

#### Approach #1 Brute Force [Time Limit Exceeded]

\n

The simplest approach makes use of a 1-d array, to keep a track of the candies given to the students. Firstly, we give 1 candy to each student. Then, we start scanning the\narray from left-to-right. At every element encountered, firstly, if the current element\'s ratings, , is larger than the previous element() and ,\nthen we update as .Thus, now the candy distribution for these two elements and becomes correct for the time being(locally).\n In the same step, we also check if the current element\'s ratings, , is larger than the next element\'s ratings,\ni.e. . If so, we again update . We continue this process for the whole array. If in any traversal,\nno updation of the array occurs, it means we\'ve reached at the final required distribution of the candies and we can stop the traversals. To keep a track of\nthis we make use of a which is set to if any updation occurs in a traversal.

\n

At the end, we can sum up all the elements of the array to obtain the required minimum number of candies.

\n\n

Complexity Analysis

\n
\n
• Time complexity : . We need to traverse the array at most times.
• \n
• Space complexity : . One array of size is used.
• \n
\n
\n

#### Approach #2 Using two arrays [Accepted]

\n

Algorithm

\n

In this approach, we make use of two 1-d arrays and . The array is used to store the number of candies required by the\ncurrent student taking care of the distribution relative to the left neighbours only. i.e. Assuming the distribution rule is: The student with a higher ratings\nthan its left neighbour should always get more candies than its left neighbour. Similarly, the array is used to store the number of candies candies required by the\ncurrent student taking care of the distribution relative to the right neighbours only. i.e. Assuming the distribution rule to be: The student with a higher ratings\nthan its right neighbour should always get more candies than its right neighbour. To do so, firstly we assign 1 candy to each student in both and array.\n Then, we traverse the array from\nleft-to-right and whenever the current element\'s ratings is larger than the left neighbour we update the\ncurrent element\'s candies in the array as , since the current element\'s candies are always less than or equal candies than its left neighbour before updation.\nAfter the forward traversal, we traverse the array from left-to-right and\nupdate as , whenever the current() element has a higher ratings than the\nright() element.

\n

Now, for the student in the array, we need to give to it, in order to satisfy both the left and the right neighbour\nrelationship. Thus, at the end, we obtain the minimum number of candies required as:

\n

\n\n

\n

The following animation illustrates the method:

\n

\n\n

Complexity Analysis

\n
\n
• \n

Time complexity : . and arrays are traversed thrice.

\n
• \n
• \n

Space complexity : . Two arrays and of size are used.

\n
• \n
\n
\n

#### Approach #3 Using one array [Accepted]

\n

Algorithm

\n

In the previous approach, we used two arrays to keep track of the left neighbour and the right neighbour relation individually and later on combined these two. Instead of this, we\ncan make use of a single array to keep the count of the number of candies to be allocated to the current student. In order to do so, firstly we assign 1 candy to\neach student. Then, we traverse the array from left-to-right and distribute the candies following only the left neighbour relation i.e. whenever the current element\'s ratings is\nlarger than the left neighbour and has less than or equal candies than its left neighbour, we update the\ncurrent element\'s candies in the array as . While updating we need not compare and , since\n before updation. After this, we traverse the array from right-to-left. Now, we need to\nupdate the element\'s candies in order to satisfy both the left neighbour and the right neighbour relation. Now, during the backward traversal, if ,\nconsidering only the right neighbour criteria, we could\'ve updated as . But, this time we need to update the only\nif . This happens because, this time we\'ve already altered the array during the forward traversal and thus isn\'t\nnecessarily less than or equal to . Thus, if , we can update as , which makes\n satisfy both the left neighbour and the right neighbour criteria.

\n

Again, we need sum up all the elements of the array to obtain the required result.

\n

\n\n

\n\n

Complexity Analysis

\n
\n
• \n

Time complexity : . The array of size is traversed thrice.

\n
• \n
• \n

Space complexity : . An array of size is used.

\n
• \n
\n
\n

#### Approach #4 Single Pass Approach with Constant Space [Accepted]

\n

Algorithm

\n

This approach relies on the observation(as demonstrated in the figure below as well) that in order to distribute the candies as per the given criteria using\nthe minimum number of candies, the candies are always distributed in terms of increments of 1. Further, while distributing the candies, the local minimum number of candies\ngiven to a student is 1. Thus, the sub-distributions always take the form: or , whose sum is simply given by .

\n

Now, we can view the given as some\nrising and falling slopes. Whenever the slope is rising, the distribution takes the form: . Similarly, a falling slope takes the form:\n. An issue that arises now is that the local peak point can be included in only one of the slopes.\nWhether to include the local peak point() in the rising slope or the falling slope?

\n

In order to decide it,\nwe can observe that in order to satisfy both the right neighbour and the left neighbour criteria, the peak point\'s count needs to be the max. of the counts determined\nby the rising and the falling slopes. Thus, in order to determine the number of candies required, the peak point needs to be included in the slope which contains more\nnumber of points. The local valley point can also be included in only one of the slopes, but this issue can be resolved easily, since the local valley point will\nalways be assigned a candy count of 1(which can be subtracted from the next slope\'s count calculations).

\n

Coming to the implementation, we maintain two variables and to determine the occurence of a peak or a valley. We also use\n and variables to keep a track of the count of elements on the rising slope and on the falling slope respectively(without including the peak element). We always update the total count\nof at the end of a falling slope following a rising slope (or a mountain). The leveling of the points in also works as the end of a mountain. At the end of the mountain, we determine whether to include the peak point in the rising slope or in the falling slope by comparing the and variables up to that point. Thus, the count assigned to the peak element becomes: . At this point, we can reset the and variables indicating the start of a new mountain.

\n

The following figure shows the cases that need to be handled for this example:

\n

rankings: [1 2 3 4 5 3 2 1 2 6 5 4 3 3 2 1 1 3 3 3 4 2]

\n

\n

From this figure, we can see that the candy distributions in the subregions always take the form or .\nFor the first mountain comprised by the regions and , while assigning candies to the local peak point(), it needs to be included in\n to satisfy the left neighbour criteria. The local valley point at the end of region () marks the end of the first mountain(region ).\n While performing the calculations, we can include this point in either the current or the following mountain. The marks the end of the second\n mountain due to levelling of the and . Since, region has more points than region , the local peak() needs to be\n included in region to satisfy the right neighbour criteria. Now, the third mountain can be considered as a mountian with no rising slope()\n but only a falling slope. Similarly, also act as the mountain ends due to the levelling of the points.

\n\n

Complexity Analysis

\n
\n
• \n

Time complexity : . We traverse the array once only.

\n
• \n
• \n

Space complexity : . Constant Extra Space is used.

\n
• \n
\n
\n

Analysis written by: @vinod23

\n
'