Magnetic Force Between Two Balls LeetCode solution in Python

1
class Solution:
2
def possible(self, distance, positions, M):
3
ball = 1
4
lastPos = positions[0]
5
for pos in positions:
6
if pos - lastPos >= distance:
7
ball += 1
8
if ball == M:
9
return True
10
lastPos = pos
11

12
return False
13

14
def maxDistance(self, positions, M):
15
positions.sort()
16
low = 0
17
high = positions[-1]
18
ans = 0
19
while low <= high:
20
distance = low + (high - low) // 2
21

22
if self.possible(distance, positions, M):
23
ans = distance
24
low = distance + 1
25
else:
26
high = distance - 1
27
return ans

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0