Skip to content

Commit 37f9421

Browse files
committed
Add solution #1552
1 parent 78b45e6 commit 37f9421

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,362 LeetCode solutions in JavaScript
1+
# 1,363 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1185,6 +1185,7 @@
11851185
1547|[Minimum Cost to Cut a Stick](./solutions/1547-minimum-cost-to-cut-a-stick.js)|Hard|
11861186
1550|[Three Consecutive Odds](./solutions/1550-three-consecutive-odds.js)|Easy|
11871187
1551|[Minimum Operations to Make Array Equal](./solutions/1551-minimum-operations-to-make-array-equal.js)|Medium|
1188+
1552|[Magnetic Force Between Two Balls](./solutions/1552-magnetic-force-between-two-balls.js)|Medium|
11881189
1566|[Detect Pattern of Length M Repeated K or More Times](./solutions/1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy|
11891190
1576|[Replace All ?'s to Avoid Consecutive Repeating Characters](./solutions/1576-replace-all-s-to-avoid-consecutive-repeating-characters.js)|Medium|
11901191
1598|[Crawler Log Folder](./solutions/1598-crawler-log-folder.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* 1552. Magnetic Force Between Two Balls
3+
* https://leetcode.com/problems/magnetic-force-between-two-balls/
4+
* Difficulty: Medium
5+
*
6+
* In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls
7+
* if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at
8+
* position[i], Morty has m balls and needs to distribute the balls into the baskets such that
9+
* the minimum magnetic force between any two balls is maximum.
10+
*
11+
* Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
12+
*
13+
* Given the integer array position and the integer m. Return the required force.
14+
*/
15+
16+
/**
17+
* @param {number[]} position
18+
* @param {number} m
19+
* @return {number}
20+
*/
21+
var maxDistance = function(position, m) {
22+
position.sort((a, b) => a - b);
23+
24+
let left = 1;
25+
let right = position[position.length - 1] - position[0];
26+
let result = 0;
27+
28+
while (left <= right) {
29+
const mid = Math.floor((left + right) / 2);
30+
if (canPlaceBalls(mid)) {
31+
result = mid;
32+
left = mid + 1;
33+
} else {
34+
right = mid - 1;
35+
}
36+
}
37+
38+
return result;
39+
40+
function canPlaceBalls(minForce) {
41+
let count = 1;
42+
let lastPos = position[0];
43+
44+
for (let i = 1; i < position.length; i++) {
45+
if (position[i] - lastPos >= minForce) {
46+
count++;
47+
lastPos = position[i];
48+
}
49+
}
50+
51+
return count >= m;
52+
}
53+
};

0 commit comments

Comments
 (0)