Concise Java Solution
In the forward pass, if we meet r[i] < r[i+1] , assign candy[i+1] = candy[i]+1;\n\nIn the backward pass, the only difference is the case when r[i-1] < r[i] > r[
In the forward pass, if we meet r[i] < r[i+1] , assign candy[i+1] = candy[i]+1;\n\nIn the backward pass, the only difference is the case when r[i-1] < r[i] > r[i+1], need to compare candy[i+1]+1, and candy[i] (which is calculated in forward side).\n\n\n    public class Solution {\n        public int candy(int[] ratings) {\n            // initialize\n            int candy[] = new int[ratings.length];\n            int sum = 0;\n            Arrays.fill(candy,1); // crucial step!\n            \n            // forward pass, assign candy for increasing ones\n            for(int i = 1;i < ratings.length;i++)\n                if(ratings[i] > ratings[i-1])\n                    candy[i] = candy[i-1]+1;\n                    \n            // backforward pass, assign candy for decreasing ones\n            for(int i = ratings.length-2;i >= 0;i--)\n                if(ratings[i] > ratings[i+1]){\n                    if(i-1 >= 0 && ratings[i-1] <= ratings[i])\n                        candy[i] = Math.max(candy[i+1]+1, candy[i]);\n                    else\n                        candy[i] = candy[i+1] + 1;\n                }\n            \n            // sum up candy\n            for(int i = 0;i < candy.length;i++)\n                sum += candy[i];\n            return sum;\n        }\n    }
['Java']