From de4c2963fd2c12e11176842018f7cccb1cab4b38 Mon Sep 17 00:00:00 2001 From: AjanthaRamineni Date: Sun, 21 Nov 2021 16:51:24 -0800 Subject: [PATCH] Update 1552. Magnetic Force Between Two Balls --- 1000+/1552. Magnetic Force Between Two Balls | 33 ++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/1000+/1552. Magnetic Force Between Two Balls b/1000+/1552. Magnetic Force Between Two Balls index ed6240b..32b0485 100644 --- a/1000+/1552. Magnetic Force Between Two Balls +++ b/1000+/1552. Magnetic Force Between Two Balls @@ -30,3 +30,36 @@ class Solution { return count >= m; } } + + +class Solution { + public int maxDistance(int[] position, int m) { + Arrays.sort(position); + int low = 0; + int high = position[position.length-1]; + while (low < high) { + int mid = low + (high-low+1)/2; + if (canPut(position, m, mid)) { + low = mid; + } else { + high = mid-1; + } + } + return low; + } + + /* + * returns whether we can put m balls such that minimum distance between two consecutive ball is always greater than or equal to the max. + */ + private boolean canPut(int[] positions, int m, int max) { + int count = 1; + int last = positions[0]; + for (int i = 0; i < positions.length; i++) { + if (positions[i] - last >= max) { + last = positions[i]; + count++; + } + } + return count >= m; + } +}