Very simple approach with explained theory and code using one array O(n)
To solve this problem we will traverse the Rating array two times , Once Left to right ,second\nRight to left\nFirst we will make a resultant array equal to the
**To solve this problem we will traverse the Rating array two times , Once Left to right ,second\nRight to left\nFirst we will make a resultant array equal to the size of ratings and fill it with 1 at every index\nWhile Traversing left to right we will start from 2nd element and check if this is greater then prev elem then we will increase resultant array[i] = resultant[i-1]+1\nNow second traversal \nwe will start from right second element and check if  this is greater then next element  then we will check further if res[i]<=res[i+1] then we will inc res[i]=  res[i+1]+1\nNow we will traverse the res array and return sum of its element\nNow below is the code \nDo Upvote please!  :)\nHappy Leetcoding**\n\n```\nclass Solution {\n    public int candy(int[] ratings) {\n        int n = ratings.length;\n        int[] res = new int[n];\n        Arrays.fill(res,1);\n        //Left to right scan and check whether ratings[i]>ratings[i-1] if yes then increment by res[i-1]+1\n        for(int i=1;i<n;i++){\n            if(ratings[i]>ratings[i-1]){\n                res[i] = res[i-1]+1;\n            }\n        }\n        \n        System.out.println(Arrays.toString(res));\n        // Right to left scan and check whether raings[i]>ratings[i+1] if yes then check whether res[i]<=res[i+1] \n        //inc by res[i+1]+1\n        for(int i=n-2;i>=0;i--){\n            if(ratings[i]>ratings[i+1]){\n                if(res[i]<=res[i+1]){\n                    res[i] = res[i+1]+1;\n                }\n            }\n        }\n        int cnt=0;\n        for(int i=0;i<n;i++){\n            cnt+=res[i];\n        }\n        return cnt;\n    }\n}\n```
['Array', 'Java']