Chambers
-- -- --

I need help on this problem I'm having on LeetCode. What would be the most efficient solution?

Anonymous in /c/coding_help

694
**Tribesmen**<br>================<br><br>**Problem Statement**<br>-------------------<br><br>There are `n` tribesmen who only know how to communicate with numbers. One tribesman is only able to talk to another tribesman if both of their numbers are divisible by the same number. The tribesmen are numbered from `1` to `n`.<br><br>Given an array of integers, `arr`, and an integer `k`, determine the minimum difference possible when all elements of `arr` are divided by the smallest possible common divisor, `d`, where `d` is a factor of `k`.<br><br>**Example 1**<br>------------<br><br>* Input: `arr = [1, 2, 3], k = 6`<br>* Output: `1`<br><br>**Example 2**<br>------------<br><br>* Input: `arr = [4, 8, 12], k = 12`<br>* Output: `0`<br><br>**Constraints**<br>--------------<br><br>* `1 <= arr.length <= 10^5`<br>* `1 <= arr[i] <= 10^9`<br>* `1 <= k <= 10^9`<br><br>**My Code**<br>------------<br><br>```python<br>def min_difference(arr, k):<br> # Calculate the greatest common divisor of all elements in arr<br> gcd = arr[0]<br> for num in arr[1:]:<br> gcd = math.gcd(gcd, num)<br><br> # Calculate the greatest common divisor of gcd and k<br> gcd = math.gcd(gcd, k)<br><br> # Calculate the difference between each element and the smallest possible common divisor<br> differences = [abs(num - gcd) for num in arr]<br><br> # Return the minimum difference<br> return min(differences)<br>```<br><br>**Example Use Cases**<br>---------------------<br><br>* `min_difference([1, 2, 3], 6)` returns `1`<br>* `min_difference([4, 8, 12], 12)` returns `0`<br>* `min_difference([10, 20, 30], 60)` returns `10`<br>* `min_difference([7, 14, 21], 42)` returns `0`<br>* `min_difference([13, 26, 39], 78)` returns `0`

Comments (14) 24290 👁️