Advertisement

Find the Maximum Divisibility Score - LeetCode 2644 Solution

Find the Maximum Divisibility Score - Complete Solution Guide

Find the Maximum Divisibility Score is LeetCode problem 2644, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

You are given two 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 multiple integers have the maximum score, return the smallest one. Example 1: Input: nums = [2,9,15,50], divisors = [5,3,7,2] Output: 2 Explanation: The divisibility score of divisors[0] is 2 since nums[2] and nums[3] are divisible by 5. The divisibility score of

Detailed Explanation

The problem asks to find the divisor from the `divisors` array that has the maximum divisibility score. The divisibility score of a divisor is the number of elements in the `nums` array that are divisible by that divisor. If multiple divisors have the same maximum score, the smallest one should be returned.

Solution Approach

The solution uses a brute-force approach. It iterates through each divisor in the `divisors` array. For each divisor, it iterates through the `nums` array and counts the numbers divisible by the current divisor. This count becomes the divisibility score for that divisor. The algorithm keeps track of the maximum score seen so far and the corresponding divisor. If a divisor achieves a higher score, it updates the maximum score and the best divisor. If a divisor has the same maximum score, it selects the smaller divisor. Finally, it returns the divisor with the maximum divisibility score.

Step-by-Step Algorithm

  1. Initialize `max_score` to -1 and `result` to positive infinity (or a very large number) to handle the initial comparison.
  2. Iterate through each `divisor` in the `divisors` array.
  3. For each `divisor`, iterate through each `num` in the `nums` array.
  4. If `num` is divisible by `divisor` ( `num % divisor == 0`), increment the `score`.
  5. After iterating through all `nums`, if `score` is greater than `max_score`, update `max_score` to `score` and `result` to `divisor`.
  6. If `score` is equal to `max_score`, update `result` to the minimum of `result` and `divisor`.
  7. After iterating through all divisors, return `result`.

Key Insights

  • Iterate through each divisor and count how many numbers in `nums` are divisible by it.
  • Maintain the maximum score encountered so far and the corresponding divisor.
  • If a divisor has the same maximum score as the current best, choose the smaller divisor.

Complexity Analysis

Time Complexity: O(n*m)

Space Complexity: O(1)

Topics

This problem involves: Array.

Companies

Asked at: DE Shaw.