|
| 1 | +# [1552. Magnetic Force Between Two Balls](https://leetcode.com/problems/magnetic-force-between-two-balls) |
| 2 | + |
| 3 | +--- |
| 4 | + |
| 5 | +title: "Maximize Minimum Distance Between Balls" |
| 6 | +summary: "This document provides a solution to maximize the minimum distance between balls placed in baskets, using a binary search approach." |
| 7 | +date: 2024-06-20 |
| 8 | +modified_date: 2024-06-20 |
| 9 | +tags: ["algorithm", "binary search", "greedy", "JavaScript"] |
| 10 | +slug: "maximize-minimum-distance-between-balls" |
| 11 | + |
| 12 | +--- |
| 13 | + |
| 14 | +# Intuition |
| 15 | + |
| 16 | +The goal is to maximize the minimum distance between any two balls placed in baskets. By leveraging binary search, we can efficiently determine the largest possible minimum distance. |
| 17 | + |
| 18 | +# Approach |
| 19 | + |
| 20 | +1. **Sort the Positions**: Start by sorting the array of basket positions. |
| 21 | +2. **Binary Search**: Use binary search to find the maximum minimum distance. |
| 22 | +3. **Validation Function**: Implement a helper function to check if a given minimum distance is valid by trying to place all the balls with at least that distance apart. |
| 23 | + |
| 24 | +# Complexity |
| 25 | + |
| 26 | +- Time complexity: \(O(n \log d)\), where \(n\) is the number of baskets and \(d\) is the difference between the maximum and minimum positions in the array. |
| 27 | + |
| 28 | +- Space complexity: \(O(1)\), as we are using only a fixed amount of extra space. |
| 29 | + |
| 30 | +# Code |
| 31 | + |
| 32 | +```javascript |
| 33 | +/** |
| 34 | + * @param {number[]} position |
| 35 | + * @param {number} m |
| 36 | + * @return {number} |
| 37 | + */ |
| 38 | +function maxDistance(position, m) { |
| 39 | + position.sort((a, b) => a - b); |
| 40 | + |
| 41 | + const isValid = (minDist) => { |
| 42 | + let count = 1; // Place the first ball in the first basket |
| 43 | + let lastPos = position[0]; |
| 44 | + |
| 45 | + for (let i = 1; i < position.length; i++) { |
| 46 | + if (position[i] - lastPos >= minDist) { |
| 47 | + count++; |
| 48 | + lastPos = position[i]; |
| 49 | + } |
| 50 | + if (count >= m) { |
| 51 | + return true; |
| 52 | + } |
| 53 | + } |
| 54 | + return false; |
| 55 | + }; |
| 56 | + |
| 57 | + let left = 1; |
| 58 | + let right = position[position.length - 1] - position[0]; |
| 59 | + |
| 60 | + while (left <= right) { |
| 61 | + let mid = Math.floor((left + right) / 2); |
| 62 | + if (isValid(mid)) { |
| 63 | + left = mid + 1; |
| 64 | + } else { |
| 65 | + right = mid - 1; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return right; |
| 70 | +} |
| 71 | +``` |
0 commit comments