We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
My Java 8 solution, passing all test cases, for a Max Score of 50:
The code is fairly simple & self-explanatory.
publicstaticlongcandies(intn,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=newint[n];int[]dpR=newint[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 Loopfor(inti=1,j=(n-2);(i<n)||(j>=0);i++,j--){// DP from Left to Rightif(i<n&&arr.get(i)>arr.get(i-1)){dpL[i]=dpL[i-1]+1;}// DP from Right to Leftif(j>=0&&arr.get(j)>arr.get(j+1)){dpR[j]=dpR[j+1]+1;}}// Combine 'dpL' & 'dpR' resultslongminTotalCandies=0;for(inti=0;i<n;i++){minTotalCandies+=Math.max(dpL[i],dpR[i]);}returnminTotalCandies;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Candies
You are viewing a single comment's thread. Return to all comments →
My Java 8 solution, passing all test cases, for a Max Score of 50:
The code is fairly simple & self-explanatory.