💥[EXPLAINED] Runtime beats 98.73%, Memory beats 45.65%
Intuition\nGive each child at least one candy, then adjust so higher-rated children get more than their neighbors.\n\n# Approach\nInitialize: Start with 1 candy
# Intuition\nGive each child at least one candy, then adjust so higher-rated children get more than their neighbors.\n\n# Approach\nInitialize: Start with 1 candy for each child.\n\nLeft to Right: Increase candies if a child\u2019s rating is higher than the previous one.\n\nRight to Left: Adjust candies if a child\u2019s rating is higher than the next one.\n\nSum Up: Add all candies.\n\n# Complexity\n- Time complexity:\nO(n), where n is the number of children. Each pass through the ratings array takes linear time, and there are two passes.\n\n- Space complexity:\nO(n), where n is the number of children. An additional array of size n is used to keep track of the candy count for each child.\n\n# Code\n```typescript []\nfunction candy(ratings: number[]): number {\n    const n = ratings.length;\n    if (n === 0) return 0;\n\n    // Step 1: Initialize the candies array where each child gets at least 1 candy.\n    const candies = new Array(n).fill(1);\n\n    // Step 2: Left to right pass\n    for (let i = 1; i < n; i++) {\n        if (ratings[i] > ratings[i - 1]) {\n            candies[i] = candies[i - 1] + 1;\n        }\n    }\n\n    // Step 3: Right to left pass\n    for (let i = n - 2; i >= 0; i--) {\n        if (ratings[i] > ratings[i + 1]) {\n            candies[i] = Math.max(candies[i], candies[i + 1] + 1);\n        }\n    }\n\n    // Step 4: Calculate the total number of candies\n    return candies.reduce((sum, candy) => sum + candy, 0);\n}\n\n```
['TypeScript']