💯Simple Approach 🖤 Always for You
Intuition\n Describe your first thoughts on how to solve this problem. \nWe distribute candies in two passes, left-to-right and right-to-left, ensuring higher-r
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n*We distribute candies in two passes, ```left-to-right and right-to-left```, ensuring higher-rated children get more while meeting constraints. This approach maintains two arrays (`left` and `right`) to guarantee maximum candies for each child, satisfying both the "at least one candy" and "higher than neighbors" constraints. It minimizes the total number of candies needed.*\n# Approach\n<!-- Describe your approach to solving the problem. -->\n*Step-1 -> Create arrays ```left``` and ```right``` filled with 1\'s for initial candies.\nStep-2 -> Traverse ratings ```left to right``` and check if ```current > previous rating if so add a candy to previous``` , incrementing left for higher ratings.\nStep-3 -> Traverse ratings ```right to left``` and check if ```current rating > next if so add a candy to next```, incrementing right for higher ratings.\nStep-4 -> Initialize totalCandies to 0.\nStep-5 -> Iterate arrays, adding ```max of left and right``` to totalCandies.\nStep-6 -> Return ```totalCandies``` as the minimum total candies needed.*\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n    public int candy(int[] ratings) {\n        int n = ratings.length;\n        int[] left = new int[n];\n        Arrays.fill(left,1);\n        for(int i=1; i<n; i++){\n            if(ratings[i] > ratings[i-1]) left[i] = left[i-1]+1;      \n        }\n        int[] right = new int[n];\n        Arrays.fill(right,1);\n        for(int i=n-2; i>=0; i--){\n            if(ratings[i] > ratings[i+1]) right[i] = right[i+1]+1;\n        }\n        int totalCandies = 0;\n        for(int i=0; i<n; i++){\n            totalCandies += Math.max(left[i],right[i]);\n        }\n        return totalCandies;\n    }\n}\n```
['Java']