




Sponsored
Sponsored
The idea behind the Two-Pass Solution is to first ensure each child has more candies than the child before them if their rating is higher, and then make another pass to ensure the condition is also satisfied going from right to left. By leveraging two passes, we ensure that the candy distribution meets the requirements in both directions.
Time Complexity: O(n) - where n is the number of children, because we make two linear passes through the ratings.
Space Complexity: O(n) - where n is the number of children, due to the storage of candies array.
1class Solution:
2    def candy(self, ratings):
3        n = len(ratings)
4        candies = [1] * n
5        for i in range(1, n):
6            if ratings[i] > ratings[i - 1]:
7                candies[i] = candies[i - 1] + 1
8        for i in range(n - 2, -1, -1):
9            if ratings[i] > ratings[i + 1]:
10                candies[i] = max(candies[i], candies[i + 1] + 1)
11        return sum(candies)
12
13# Example Usage
14sol = Solution()
15print(sol.candy([1, 0, 2]))The Python solution uses list comprehensions to initialize the candies list. It conducts two passes over the `ratings` list to ensure proper candy distribution per the ratings. Finally, the `sum` function is used to calculate the total number of candies needed.
This method involves the use of two arrays to maintain the candies given on left-to-right and right-to-left conditions separately. Instead of managing passes sequentially, we compute the required candies for each condition independently, and then derive the final candy count based on maximum requirements from both arrays at each index.
Time Complexity: O(n)
Space Complexity: O(n)
1public
This Java solution also utilizes two int arrays `left` and `right`, which store information about candy requirements for each child based on rating comparison results from either side. In this way, the optimal candy distribution sum takes maximum of both conditions.