We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

- Prepare
- Algorithms
- Greedy
- Candies
- Discussions

# Candies

# Candies

#### Sort by

recency

#### |

#### 668 Discussions

#### |

Please Login in order to post a comment

No additional array used

def candies(n, arr): total = 1 peak_index=0 peak_value = 1 last_value = 1 i = 1 while iarr[j]: j +=1 i = j-1 j -=2 last_value = 1 total += last_value while j>=peak_index: if (arr[j]>arr[j+1]): last_value += 1 else: last_value=1 total += last_value j -= 1 total -= peak_value total -= last_value total += max(peak_value, last_value) last_value=1 i += 1

RIP problem description. Extremely vague.

i know there are solution L-R and R-L solution , however for practice putepose I try to solve it different . But why do my code give wrong answer

To solve this problem, we'll use a two-pass approach:

Left to Right Pass: Traverse the list from left to right. If a child has a higher rating than the previous child, increment the candy count for that child based on the previous child's candy count.Right to Left Pass: Traverse the list from right to left. If a child has a higher rating than the next child, ensure that the current child's candy count is higher than the next child's candy count.The final candy count for each child will be the maximum of the counts from the two passes.

Here's the PHP code to solve the "Candies" problem:

## Explanation

Initialization:`candies`

array with 1 candy for each child since each child must get at least one candy.Left to Right Pass:Right to Left Pass:Summing Up:`candies`

array to get the total number of candies required.This approach ensures that the distribution of candies meets the problem's constraints with a time complexity of (O(n)) and space complexity of (O(n)).

This problem was based on increasing/descreasing sequence and pure observation