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:

  • x if x >= 0
  • -x if x < 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
Minimum Garden Perimeter to Collect Enough Apples INPUT 0 1 1 1 1 2 2 2 2 (0,0) at center Tree at (i,j) has |i|+|j| apples neededApples = 1 Find min perimeter ALGORITHM STEPS 1 Square centered at origin Side length = 2n + 1 2 Calculate apples formula Total = 2n(n+1)(2n+1) 3 Binary search for n Find smallest n where apples >= neededApples 4 Perimeter = 8n Square perimeter formula For neededApples = 1: n=1: apples = 2*1*2*3 = 12 12 >= 1 [OK] perimeter = 8 * 1 = 8 FINAL RESULT 0 1 1 1 1 2 2 2 2 Square plot n=1 OUTPUT 8 Minimum perimeter = 8 Total apples inside: 12 Key Insight: The total apples in a square of half-width n centered at origin follows the closed formula: Total = 2 * n * (n+1) * (2n+1) Use binary search to find minimum n, then perimeter = 8n TutorialsPoint - Minimum Garden Perimeter to Collect Enough Apples | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
23.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen