Minimum Garden Perimeter to Collect Enough Apples LeetCode solution in JavaScript
1/**2* @param {number} neededApples3* @return {number}4*/5var minimumPerimeter = function (neededApples) {6let start = 2,7n = 1,8dp = [0];910while (true) {11let cur = start,12res = dp[n - 1];1314//Add the X and Y axis apples multiplied with 415res += (cur + cur - n) * 4;1617// Add the interior apples using and AP formula of ( n - 1 ) / 2 * (2a + ( n-1 ) * d ) & multiplying it by 8 as count is 818res += ((n - 1) / 2) * (2 * (cur - 1) + (n - 2) * -1) * 8;1920//Setting the result to DP21dp[n] = res;2223//If current state is greater than or equal to needed then return the perimeter24if (neededApples <= res) return 8 * n;25n++;26start += 2;27}28};