




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.
1function candy(ratings) {
2    const n = ratings.length;
3    const candies = new Array(n).fill(1);
4    for (let i = 1; i < n; ++i) {
5        if (ratings[i] > ratings[i - 1]) {
6            candies[i] = candies[i - 1] + 1;
7        }
8    }
9    for (let i = n - 2; i >= 0; --i) {
10        if (ratings[i] > ratings[i + 1]) {
11            candies[i] = Math.max(candies[i], candies[i + 1] + 1);
12        }
13    }
14    return candies.reduce((sum, a) => sum + a, 0);
15}
16
17// Example usage
18console.log(candy([1, 0, 2]));The JavaScript solution comprises two main loops which firstly manage assigning candies based on the increasing order of ratings, and then modify them based on their decreasing order. Finally, the total count of candies is returned using the `reduce` method.
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)
1#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int candy(vector<int>& ratings) {
    int n = ratings.size();
    vector<int> left(n, 1), right(n, 1);
    for (int i = 1; i < n; ++i) {
        if (ratings[i] > ratings[i - 1])
            left[i] = left[i - 1] + 1;
    }
    for (int i = n - 2; i >= 0; --i) {
        if (ratings[i] > ratings[i + 1])
            right[i] = right[i + 1] + 1;
    }
    int totalCandy = 0;
    for (int i = 0; i < n; ++i) {
        totalCandy += max(left[i], right[i]);
    }
    return totalCandy;
}
int main() {
    vector<int> ratings = {1, 0, 2};
    cout << candy(ratings) << endl;
    return 0;
}For the C++ solution, two vectors `left` and `right` keep track of required candies due to left and right comparisons, respectively. The final candy count is computed by considering the maximum value at each index between the two vectors.