✅5 lines of efficient code | step by step approach
Intuition\nMy initial thoughts on how to solve this problem are to iterate through the ratings array and compare each element with its neighboring elements. If 
# Intuition\nMy initial thoughts on how to solve this problem are to iterate through the ratings array and compare each element with its neighboring elements. If an element is greater than its previous element, I would assign it one more candy than the previous element. Similarly, if an element is greater than its next element, I would assign it one more candy than the next element. This way, I can ensure that higher-rated students receive more candies than their neighbors.\n\n# Approach\nTo solve the problem, I will use a greedy approach. I will initialize a result variable as 0 to keep track of the total number of candies needed. I will also create two arrays, ltr and rtl, both of length n (where n is the number of elements in the ratings array). The ltr array will store the number of candies assigned to each student from left to right, and the rtl array will store the number of candies assigned to each student from right to left.\n\nFirst, I will iterate through the ratings array from index 1 to n-1. If the current rating is greater than the previous rating, I will assign one more candy than the previous student to the current student by updating the ltr array.\n\nThen, I will iterate through the ratings array from index n-2 to 0. If the current rating is greater than the next rating, I will assign one more candy than the next student to the current student by updating the rtl array.\n\nFinally, I will iterate through the ratings array and add the maximum value between ltr[i] and rtl[i] to the result variable.\n\nAfter the iterations, the result variable will contain the minimum number of candies needed to satisfy the given conditions. I will return this result.\n\n# Complexity\n- Time complexity: The time complexity of this solution is O(n), where n is the number of elements in the ratings array. This is because we iterate through the ratings array three times, which takes linear time.\n- Space complexity: The space complexity is also O(n) because we create two arrays, ltr and rtl, of length n to store the number of candies assigned to each student.\n\n# Code\n```\nfunction candy(ratings: number[]): number {\n    let res = 0 , n = ratings.length, ltr = new Array(n).fill(1) , rtl = new Array(n).fill(1);\n    for( let i = 1 ; i < n ; i++ )if( ratings[i] > ratings[i - 1])ltr[i] = ltr[i - 1] + 1;\n    for( let i = n - 2 ; i >= 0 ; i-- )if( ratings[i] > ratings[i + 1])rtl[i] = rtl[i + 1] + 1;\n    for( let i = 0 ; i < n ; i++ )res += Math.max(ltr[i] , rtl[i])\n    return res;\n};\n```
['Array', 'Greedy', 'TypeScript', 'JavaScript']