From 7d56ecae0104302bf9bf5260455e147956e7a438 Mon Sep 17 00:00:00 2001 From: Johan Sandoval Date: Sat, 25 Jul 2026 14:08:11 -0500 Subject: [PATCH] Finish problem 1552-magnetic-force-between-two-balls --- .../solution.py | 23 +++++++++++++++++++ .../solution_test.py | 13 +++++++++++ 2 files changed, 36 insertions(+) create mode 100644 problems/1552-magnetic-force-between-two-balls/solution.py create mode 100644 problems/1552-magnetic-force-between-two-balls/solution_test.py diff --git a/problems/1552-magnetic-force-between-two-balls/solution.py b/problems/1552-magnetic-force-between-two-balls/solution.py new file mode 100644 index 0000000..107ee29 --- /dev/null +++ b/problems/1552-magnetic-force-between-two-balls/solution.py @@ -0,0 +1,23 @@ +def balls_able(sorted_positions: list[int], min_distance) -> int: + balls = 1 + anchor = sorted_positions[0] + for position in sorted_positions[1:]: + if position - anchor >= min_distance: + balls += 1 + anchor = position + + return balls + + +class Solution: + def maxDistance(self, position: list[int], m: int) -> int: + sorted_positions = sorted(position) + lo, hi = 1, max(position) - min(position) + while lo < hi: + limit = (lo + hi + 1) // 2 + if balls_able(sorted_positions, limit) >= m: + lo = limit + else: + hi = limit - 1 + + return hi diff --git a/problems/1552-magnetic-force-between-two-balls/solution_test.py b/problems/1552-magnetic-force-between-two-balls/solution_test.py new file mode 100644 index 0000000..ae68969 --- /dev/null +++ b/problems/1552-magnetic-force-between-two-balls/solution_test.py @@ -0,0 +1,13 @@ +import pytest +from solution import Solution + + +@pytest.mark.parametrize( + "position, m, expected", + [ + ([1, 2, 3, 4, 7], 3, 3), + ([5, 4, 3, 2, 1, 1000000000], 2, 999999999), + ], +) +def test_max_distance(position, m, expected): + assert Solution().maxDistance(position, m) == expected