2644. Find the Maximum Divisibility Score

Array

Explanation

To solve this problem, we can iterate over each divisor and count the number of elements in the nums array that are divisible by that divisor. We then track the divisor with the maximum count. If there are multiple divisors with the same maximum count, we return the smallest one.

  • Initialize a map to store the count of elements divisible by each divisor.
  • Iterate over the nums array and for each element, iterate over the divisors array to check if the element is divisible by the divisor. Increment the count in the map accordingly.
  • Finally, find the divisor with the maximum count. If there are multiple divisors with the same maximum count, return the smallest one.

Time Complexity: O(N * M), where N is the length of the nums array and M is the length of the divisors array.

Space Complexity: O(M), where M is the length of the divisors array.

class Solution {
    public int maxDivisor(int[] nums, int[] divisors) {
        Map<Integer, Integer> countMap = new HashMap<>();
        
        for (int num : nums) {
            for (int divisor : divisors) {
                if (num % divisor == 0) {
                    countMap.put(divisor, countMap.getOrDefault(divisor, 0) + 1);
                }
            }
        }
        
        int maxDivisor = Integer.MAX_VALUE;
        int maxCount = 0;
        
        for (int divisor : divisors) {
            if (countMap.containsKey(divisor) && countMap.get(divisor) > maxCount) {
                maxDivisor = divisor;
                maxCount = countMap.get(divisor);
            } else if (countMap.containsKey(divisor) && countMap.get(divisor) == maxCount) {
                maxDivisor = Math.min(maxDivisor, divisor);
            }
        }
        
        return maxDivisor;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.