Minimum Garden Perimeter to Collect Enough Apples Problem
Description
LeetCode Problem 1954.
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:
xifx >= 0-xifx < 0
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
Constraints:
1 <= neededApples <= 10^15
Solution
Approach: Enumeration
A square garden with half-side x centred at the origin contains the trees with |i| <= x and |j| <= x, and the tree at (i, j) has |i| + |j| apples. Summing over the square gives 2 * x * (x + 1) * (2 * x + 1) apples in total.
This grows quickly with x, so we try x = 1, 2, 3, ... until the total reaches neededApples (it stays below about 10^5 steps for the largest input). The perimeter is 8 * x.
Complexity: O(neededApples^(1/3)) time and O(1) space. (Binary search on x also works.)
class Solution:
def minimumPerimeter(self, neededApples: int) -> int:
x = 1
while 2 * x * (x + 1) * (2 * x + 1) < neededApples:
x += 1
return x * 8