#1954

Minimum Garden Perimeter to Collect Enough Apples

specialist · 805 · lc medium +31 · verified · 55.5% accepted · 407 likes · top 49%

Description

An infinite garden has apple trees at every integer coordinate. The tree at (i, j) produces |i| + |j| apples. You want to buy a square plot centered at the origin ((0, 0)).

Given the integer neededApples, return the minimum perimeter of such a square plot that encloses at least neededApples apples (on or strictly inside the perimeter).

Example 1:

Input: neededApples = 1
Output: 8
Explanation: A square plot of side length 1 does not contain any apples.
However, a square plot of side length 2 has 12 apples inside (as depicted in the image above).
The perimeter is 2 * 4 = 8.

Example 2:

Input: neededApples = 13
Output: 16

Example 3:

Input: neededApples = 1000000000
Output: 5040

Code

1
2
3