#3464

Maximize the Distance Between Points on a Square

Hard
ArrayMathBinary SearchGeometrySortingBinary SearchGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

Use binary search to find the maximum possible minimum Manhattan distance. This reduces the number of combinations we need to check.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort points based on their coordinates in a clockwise manner around the square.
  2. 2Step 2: Use binary search to determine the maximum minimum distance, checking if it's possible to select k points with at least that distance apart.
  3. 3Step 3: For each distance in the binary search, use a greedy approach to select points that satisfy the distance condition.
solution.py15 lines
1def max_min_distance_optimal(side, points, k):
2    points.sort(key=lambda p: (p[0], p[1]))
3    def can_place(distance):
4        count, last = 1, points[0]
5        for i in range(1, len(points)):
6            if abs(points[i][0] - last[0]) + abs(points[i][1] - last[1]) >= distance:
7                count += 1
8                last = points[i]
9        return count >= k
10    low, high = 0, 2 * side
11    while low < high:
12        mid = (low + high + 1) // 2
13        if can_place(mid): low = mid
14        else: high = mid - 1
15    return low

Complexity note: Sorting the points takes O(n log n), and the binary search with checks takes O(n), leading to an overall efficient solution.

  • 1Manhattan distance is additive and can be optimized using sorting.
  • 2Binary search helps efficiently narrow down the maximum minimum distance.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.