Candy | Java Solution | Optimized
\nclass Solution {\n    public int candy(int[] ratings) {\n        int n =  ratings.length;\n        if(n <= 1)\n            return n;\n        int up = 0,down 
```\nclass Solution {\n    public int candy(int[] ratings) {\n        int n =  ratings.length;\n        if(n <= 1)\n            return n;\n        int up = 0,down = 0;\n        int prevSlope = 0;\n        int candies = 0;\n        \n        for(int i=1;i<n;i++)\n        {\n            //calculate the slope\n            //assign -ve +iv or zero for the decreasing increasing or plain slope\n            //increasing slope = 1\n            //decreasing slope = -1\n            //plain slope = 0\n            int current_Slope = ratings[i]>ratings[i-1]?1:\n                                (ratings[i]<ratings[i-1]?-1:0);\n            //divide the mountains on 3 conditions\n            /*Condition 1:\n              If we are getting a mountain like \\/ i.e the slope is decreasing and then increasing,\n              \n            */\n            \n            /*Condition 2:\n              If we are getting a mountain like \\_ i.e the slope is decreasing and then plain,\n              \n            */\n            \n            /*Condition 3:\n                                               _\n              If we are getting mountain like /  i.e the slope is decreasing and then increasing,\n              \n            */\n            if((prevSlope<0 && current_Slope>=0) || (prevSlope>0 && current_Slope==0))\n            {\n                candies = candies + sum(up) + sum(down) + Math.max(up,down);\n                up=0;\n                down=0;\n            }\n            if(current_Slope > 0)\n                up++;\n            else if(current_Slope < 0)\n                down++;\n            else\n                candies++;\n            prevSlope = current_Slope;\n        }\n        //add the candies that are there for the last mountain\n        candies = candies + sum(up) + sum(down) + Math.max(up,down) + 1;\n        return candies;\n    }\n    public int sum(int n)\n    {\n        return (n*(n+1))/2;\n    }\n}\n```
['Java']