Skip to content

1552. Magnetic Force Between Two Balls 👍

  • Time: $O(\texttt{sort} + n\log (\max - \min))$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
 public:
  int maxDistance(vector<int>& position, int m) {
    ranges::sort(position);

    int l = 1;
    int r = position.back() - position.front();

    while (l < r) {
      const int mid = r - (r - l) / 2;
      if (numBalls(position, mid) >= m)  // There're too many balls.
        l = mid;
      else  // There're too few balls.
        r = mid - 1;
    }

    return l;
  }

 private:
  int numBalls(const vector<int>& position, int force) {
    int balls = 0;
    int prevPosition = -force;
    for (const int pos : position)
      if (pos - prevPosition >= force) {
        ++balls;
        prevPosition = pos;
      }
    return balls;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
  public int maxDistance(int[] position, int m) {
    Arrays.sort(position);

    int l = 1;
    int r = position[position.length - 1] - position[0];

    while (l < r) {
      final int mid = r - (r - l) / 2;
      if (numBalls(position, mid) >= m) // There're too many balls.
        l = mid;
      else // There're too few balls.
        r = mid - 1;
    }

    return l;
  }

  private int numBalls(int[] position, int force) {
    int balls = 0;
    int prevPosition = -force;
    for (final int pos : position)
      if (pos - prevPosition >= force) {
        balls++;
        prevPosition = pos;
      }
    return balls;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
  def maxDistance(self, position: list[int], m: int) -> int:
    position.sort()

    l = 1
    r = position[-1] - position[0]

    def numBalls(force: int) -> int:
      balls = 0
      prevPosition = -force
      for pos in position:
        if pos - prevPosition >= force:
          balls += 1
          prevPosition = pos
      return balls

    while l < r:
      mid = r - (r - l) // 2
      if numBalls(mid) >= m:
        l = mid
      else:
        r = mid - 1

    return l