• + 0 comments

    My Java 8 solution, passing all test cases, for a Max Score of 50:

    The code is fairly simple & self-explanatory.

    public static long candies(int n, List<Integer> arr) {
            // Write your code here
            
            // dpL[i] = Min number of candies needed for child 'i' 
            //          when only considering the left neighbor constraint.
    
            // dpR[i] = Min number of candies needed for child 'i' 
            //          when only considering the right neighbor constraint.
    
            int[] dpL = new int[n];
            int[] dpR = new int[n];
    
            // Every child gets at least one candy.
            // Set dpL[i] = 1 and dpR[i] = 1 for all 'i'.
            Arrays.fill(dpL, 1);
            Arrays.fill(dpR, 1);
    
            // DP from Left to Right + DP from Right to Left in a Single Combined Loop
            for (int i = 1 , j = (n - 2) ; (i < n) || (j >= 0) ; i++, j--) {
    
                // DP from Left to Right
                if (i < n && arr.get(i) > arr.get(i - 1)) {
                    dpL[i] = dpL[i - 1] + 1;
                }
    
                // DP from Right to Left
                if (j >= 0 && arr.get(j) > arr.get(j + 1)) {
                    dpR[j] = dpR[j + 1] + 1;
                }
    
            }
    
            // Combine 'dpL' & 'dpR' results
            long minTotalCandies = 0;
            for (int i = 0; i < n; i++) {
                minTotalCandies += Math.max(dpL[i], dpR[i]);
            }
    
            return minTotalCandies;
        }