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 theminimum perimeter of a plot such that at least****neededApplesapples areinside or on the perimeter of that plot.

Input: neededApples =1Output: 8Explanation: 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 is2*4=8.
The apples in the garden are distributed such that the number of apples inside a square of side 2k (centered at (0,0)) can be calculated with a formula. We can use binary search to find the minimum k such that the total apples is at least neededApples.
classSolution {
public:longlong apples(longlong k) {
return2* k * (k +1) * (2* k +1);
}
longlongminimumPerimeter(longlong neededApples) {
longlong l =1, r =1e6, ans =0;
while (l <= r) {
longlong m = l + (r - l) /2;
if (apples(m) >= neededApples) {
ans = m;
r = m -1;
} else {
l = m +1;
}
}
return8* ans;
}
};
classSolution {
publiclongminimumPerimeter(long neededApples) {
long l = 1, r = (long)1e6, ans = 0;
while (l <= r) {
long m = l + (r - l) / 2;
long total = 2 * m * (m + 1) * (2 * m + 1);
if (total >= neededApples) {
ans = m;
r = m - 1;
} else {
l = m + 1;
}
}
return 8 * ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
funminimumPerimeter(neededApples: Long): Long {
var l = 1Lvar r = 1_000_000L
var ans = 0Lfunapples(k: Long) = 2 * k * (k + 1) * (2 * k + 1)
while (l <= r) {
val m = l + (r - l) / 2if (apples(m) >= neededApples) {
ans = m
r = m - 1 } else {
l = m + 1 }
}
return8 * ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
defminimum_perimeter(needed_apples: int) -> int:
defapples(k: int) -> int:
return2* k * (k +1) * (2* k +1)
l, r, ans =1, int(1e6), 0while l <= r:
m = l + (r - l) //2if apples(m) >= needed_apples:
ans = m
r = m -1else:
l = m +1return8* ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfnminimum_perimeter(needed_apples: i64) -> i64 {
fnapples(k: i64) -> i64 {
2* k * (k +1) * (2* k +1)
}
let (mut l, mut r, mut ans) = (1, 1_000_000, 0);
while l <= r {
let m = l + (r - l) /2;
if apples(m) >= needed_apples {
ans = m;
r = m -1;
} else {
l = m +1;
}
}
8* ans
}
}