Find the Maximum Divisibility Score

You want to find the divisor with the maximum divisibility score from the array divisors. If there are multiple divisors with the same maximum score, you want to return the smallest one.

Here’s a step-by-step guide to solve this problem:

  1. Initialize variables to keep track of the maximum divisibility score and the corresponding divisor.
  2. Iterate through the divisors array, and for each divisor, calculate its divisibility score by checking how many numbers in the nums array are divisible by it.
  3. If the current divisor’s divisibility score is higher than the current maximum score, update the maximum score and the corresponding divisor. If the score is equal to the current maximum score, update the divisor only if the current divisor is smaller.
  4. Return the divisor that corresponds to the maximum divisibility score.

Here is the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
    def maxDivScore(self, nums: List[int], divisors: List[int]) -> int:
        max_score = -1
        best_divisor = -1

        # Iterate through the divisors
        for divisor in divisors:
            # Calculate the divisibility score for the current divisor
            score = sum(1 for num in nums if num % divisor == 0)

            # If the current score is greater than the max score, update max_score and best_divisor
            if score > max_score or (score == max_score and divisor < best_divisor):
                max_score = score
                best_divisor = divisor

        return best_divisor

Explanation:

  • score = sum(1 for num in nums if num % divisor == 0) calculates the divisibility score by summing up 1 for every number in nums that is divisible by the current divisor.
  • if score > max_score or (score == max_score and divisor < best_divisor): checks whether the current divisor has a higher divisibility score or has the same score but is smaller than the current best divisor. If so, the maximum score and the best divisor are updated.
  • Finally, the code returns the divisor with the maximum divisibility score.