#2644
Find the Maximum Divisibility Score
EasyArrayHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * m) |
| Space | O(1) | O(m) |
💡
Intuition
Time O(n * m)Space O(m)
We can optimize the brute force approach by counting the divisibility scores in a single pass through the nums array for each divisor, which reduces the number of checks needed.
⚙️
Algorithm
4 steps- 1Step 1: Create a dictionary to store the divisibility scores for each divisor.
- 2Step 2: Iterate through each number in nums and for each number, check its divisibility against all divisors.
- 3Step 3: For each divisor that divides the number, increment its score in the dictionary.
- 4Step 4: After processing all numbers, find the divisor with the maximum score. In case of a tie, return the smallest divisor.
solution.py18 lines
1def max_divisibility_score(nums, divisors):
2 scores = {}
3 for n in nums:
4 for d in divisors:
5 if n % d == 0:
6 if d in scores:
7 scores[d] += 1
8 else:
9 scores[d] = 1
10 max_score = -1
11 result_divisor = float('inf')
12 for d in divisors:
13 if d in scores:
14 score = scores[d]
15 if score > max_score or (score == max_score and d < result_divisor):
16 max_score = score
17 result_divisor = d
18 return result_divisorℹ
Complexity note: This approach is more efficient than the brute force as we only check divisibility once per number for each divisor, leading to a linear relationship with respect to the number of divisors.
- 1Divisibility checks can be optimized using a counting approach.
- 2When dealing with ties, always consider the smallest divisor.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.