Leetcode 2644. Find the Maximum Divisibility Score
Given two integer arrays nums and divisors, return the divisor from divisors that has the maximum divisibility score. The divisibility score of a divisor is the number of elements in nums that are divisible by that divisor. If there is more than one divisor with the maximum score, return the smallest divisor.
nums and divisors and the range of the values within these arrays.nums and divisors are empty?
nums or divisors be negative?
nums and divisors are reasonable for an O(n * m) solution.nums and divisors are non-negative integers (assuming divisors would typically be positive for common problems of this nature).divisors list, count how many elements in nums are divisible by the divisor.#include <vector>
#include <algorithm>
#include <climits>
int maxDivisibilityScore(const std::vector<int>& nums, const std::vector<int>& divisors) {
int maxScore = 0;
int bestDivisor = INT_MAX;
for (int divisor : divisors) {
int currentScore = 0;
for (int num : nums) {
if (num % divisor == 0) {
currentScore++;
}
}
if (currentScore > maxScore) {
maxScore = currentScore;
bestDivisor = divisor;
} else if (currentScore == maxScore) {
bestDivisor = std::min(bestDivisor, divisor);
}
}
return bestDivisor;
}
n is the number of elements in nums and m is the number of elements in divisors.
nums.maxScore is initialized to 0 and bestDivisor to a very large value (INT_MAX) ensuring any real divisor will be smaller.nums are divisible by it.maxScore, it becomes the bestDivisor and updates the maxScore.bestDivisor and the current divisor is chosen.bestDivisor with the maximum score (or smallest in case of ties) is returned.By following this strategy, we ensure that the solution is both correct and efficient within the provided 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?