13. Candy
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
We can apply the approach of valley and peak problem. Peek will have maximum candy while valley have 1 candy.
Initialize candy_count = no. of childern ( bcz each children must have 1 candy )
Start the looping from 1 to arr.size() -1
if current value is equal to previous value then they have same number of Candy.
if we have increasing slope , we increase the peak value by one for each increasing element while( arr [ i ] > arr [ i - 1 ] ) peak++;
and add count_candy with peak value.
if we have decreasing slope , we increase the value of valley by one for each decreasing element while ( arr [ i ] < arr [ i - 1 ] ) valley++
and add count_candy with valley value.
count_candy = count_candy - min ( peak , valley )
Time Complexity: O(n)
Auxiliary Space Complexity: O(1)
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.