Minimum Garden Perimeter to Collect Enough Apples - Problem
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
Input & Output
Example 1 — Small Square
$
Input:
neededApples = 1
›
Output:
8
💡 Note:
The smallest square that contains at least 1 apple has radius 1. At radius 1, we have a 3×3 grid with total 12 apples, which is ≥ 1. Perimeter = 8 × 1 = 8.
Example 2 — Medium Square
$
Input:
neededApples = 13
›
Output:
16
💡 Note:
At radius 1: 12 apples (not enough). At radius 2: 60 apples (≥ 13). So minimum radius is 2, perimeter = 8 × 2 = 16.
Example 3 — Larger Square
$
Input:
neededApples = 1000000000
›
Output:
5040
💡 Note:
For very large needed apples, we use binary search to find the minimum radius efficiently. The answer is perimeter = 8 × 630 = 5040.
Constraints
- 1 ≤ neededApples ≤ 2 × 1015
Visualization
Tap to expand
Understanding the Visualization
1
Input
neededApples = 13
2
Process
Find minimum square radius containing ≥13 apples
3
Output
Return perimeter = 8 × radius
Key Takeaway
🎯 Key Insight: Use mathematical formula with binary search to efficiently find minimum square radius
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code