Find the Maximum Factor Score of Array Problem
Description
LeetCode Problem 3334.
You are given an integer array nums.
The factor score of an array is defined as the product of the LCM and GCD of all elements of that array.
Return the maximum factor score of nums after removing at most one element from it.
Note that both the LCM and GCD of a single number are the number itself, and the factor score of an empty array is 0.
Example 1:
Input: nums = [2,4,8,16]
Output: 64
Explanation:
On removing 2, the GCD of the rest of the elements is 4 while the LCM is 16, which gives a maximum factor score of 4 * 16 = 64.
Example 2:
Input: nums = [1,2,3,4,5]
Output: 60
Explanation:
The maximum factor score of 60 can be obtained without removing any elements.
Example 3:
Input: nums = [3]
Output: 9
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 30
Solution
Approach: Prefix and suffix GCD and LCM
We may remove at most one element, so there are only n + 1 candidates: the whole array, or the array without element i. The factor score is gcd times lcm.
Precompute the gcd and lcm of every suffix. Then sweep from the left keeping the gcd and lcm of the prefix before i; combining a prefix value with the suffix value starting at i + 1 gives the gcd and lcm of the array without nums[i]. Take the largest product. An empty array has score 0, which never beats a non-empty one, and the gcd of nothing is 0 and the lcm of nothing is 1, which makes the single-element case work naturally.
Complexity: O(n log M) time and O(n) space, where M is the largest value.
from math import gcd
def lcm(a: int, b: int) -> int:
return a // gcd(a, b) * b
class Solution:
def maxScore(self, nums: List[int]) -> int:
n = len(nums)
suf_gcd = [0] * (n + 1)
suf_lcm = [0] * n + [1]
for i in range(n - 1, -1, -1):
suf_gcd[i] = gcd(suf_gcd[i + 1], nums[i])
suf_lcm[i] = lcm(suf_lcm[i + 1], nums[i])
ans = suf_gcd[0] * suf_lcm[0]
pre_gcd, pre_lcm = 0, 1
for i, x in enumerate(nums):
ans = max(ans, gcd(pre_gcd, suf_gcd[i + 1]) * lcm(pre_lcm, suf_lcm[i + 1]))
pre_gcd = gcd(pre_gcd, x)
pre_lcm = lcm(pre_lcm, x)
return ans