[LeetCode] Minimum Garden Perimeter to Collect Enough Apples

1954. 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
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
long long minimumPerimeter(long long neededApples) {
long long res = 1;
while(neededApples > 0) {
long long now = ((res * 2 + 1) * (res * 2) / 2 - (res - 1) * (res) / 2 ) * 2 - res;
now = now * 4 - res * 2 * 4;
neededApples -= now;
res++;
}
return (res-1) * 8;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/24/PS/LeetCode/minimum-garden-perimeter-to-collect-enough-apples/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.