Minimum Garden Perimeter to Collect Enough Apples

In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it.

You will buy an axis-aligned square plot of land that is centered at (0, 0).

Given an integer neededApples, return the minimum perimeter of a plot such that at least neededApples apples are inside or on the perimeter of that plot.

The value of |x| is defined as:

  • x if x >= 0
  • -x if x < 0
Example 1
InputneededApples = 1
Output8
A square plot of side length 1 does not contain any apples, but a square plot of side length 2 has 12 apples inside, so its perimeter is 8.
Example 2
InputneededApples = 13
Output16
A plot with perimeter 8 contains only 12 apples, so the minimum perimeter that contains at least 13 apples is 16.

Constraints

  • 1 <= neededApples <= 10^15

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate