• + 0 comments

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

    1. 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.

    2. 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:

    <?php
    
    function candies($n, $ratings) {
        // Initialize candies array
        $candies = array_fill(0, $n, 1);
        
        // Left to right pass
        for ($i = 1; $i < $n; $i++) {
            if ($ratings[$i] > $ratings[$i - 1]) {
                $candies[$i] = $candies[$i - 1] + 1;
            }
        }
        
        // Right to left pass
        for ($i = $n - 2; $i >= 0; $i--) {
            if ($ratings[$i] > $ratings[$i + 1]) {
                $candies[$i] = max($candies[$i], $candies[$i + 1] + 1);
            }
        }
        
        // Calculate the total number of candies
        return array_sum($candies);
    }
    
    // Example usage:
    $n = 5;
    $ratings = [1, 0, 2, 1, 0];
    echo candies($n, $ratings); // Output: 7
    
    ?>
    

    Explanation

    1. Initialization:

      • We initialize the candies array with 1 candy for each child since each child must get at least one candy.
    2. Left to Right Pass:

      • Traverse the array from left to right. If a child’s rating is greater than the previous child's rating, the current child should get more candies than the previous child. Hence, update the candies count for the current child.
    3. Right to Left Pass:

      • Traverse the array from right to left. If a child’s rating is greater than the next child's rating, ensure that the current child’s candy count is greater than the next child’s candy count by updating if necessary.
    4. Summing Up:

      • Finally, sum up all the values in the 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)).