You are given two 0-indexed integer arrays nums
and divisors
.
The divisibility score of divisors[i]
is the number of indices j
such that nums[j]
is divisible by divisors[i]
.
Return the integer divisors[i]
with the maximum divisibility score. If there is more than one integer with the maximum score, return the minimum one.
Example 1:
Input: nums = [4,7,9,3,9], divisors = [5,2,3]
Output: 3
Explanation: The divisibility score for every element in divisors is:
The divisibility score for divisors[0] is 0 since no number in nums is divisible by 5.
The divisibility score for divisors[1] is 1 since only nums[0] is divisible by 2.
The divisibility score for divisors[2] is 3 since nums[2], nums[3], and nums[4] are divisible by 3.
Since divisors[2] has the maximum divisibility score, we return 3.
Example 2:
Input: nums = [20,14,21,10], divisors = [5,7,5]
Output: 5
Explanation: The divisibility score for every element in divisors is:
The divisibility score for divisors[0] is 2 since nums[0] and nums[3] are divisible by 5.
The divisibility score for divisors[1] is 2 since nums[1] and nums[2] are divisible by 7.
The divisibility score for divisors[2] is 2 since nums[0] and nums[3] are divisible by 5.
Since divisors[0], divisors[1], and divisors[2] all have the same maximum divisibility score, we return the minimum one which is 5.
Constraints:
Before proceeding, let’s clarify some questions:
nums
array and check divisibility.Here’s the Python code to solve this problem:
def maxDivScore(nums, divisors):
max_score = 0
optimal_divisor = float('inf')
for divisor in divisors:
score = sum(1 for num in nums if num % divisor == 0)
if score > max_score or (score == max_score and divisor < optimal_divisor):
max_score = score
optimal_divisor = divisor
return optimal_divisor
# Example usage:
nums1 = [4, 7, 9, 3, 9]
divisors1 = [5, 2, 3]
print(maxDivScore(nums1, divisors1)) # Output: 3
nums2 = [20, 14, 21, 10]
divisors2 = [5, 7, 5]
print(maxDivScore(nums2, divisors2)) # Output: 5
Let’s analyze the time complexity of our algorithm:
divisors
array.nums
array to count divisibility, which takes (O(n)) time where (n) is the length of the nums
array.Thus, the overall time complexity is (O(n \times d)), which is efficient given the constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?