#3334

Find the Maximum Factor Score of Array

Medium
ArrayMathNumber TheoryGCD/LCM calculationsPrefix/Suffix arrays
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

By using prefix and suffix arrays, we can compute the GCD and LCM of the entire array while excluding one element, avoiding the need for repeated calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create prefix and suffix arrays for GCD and LCM.
  2. 2Step 2: For each element, calculate the GCD and LCM of the remaining elements using the prefix and suffix arrays.
  3. 3Step 3: Compute the factor score and track the maximum score.
solution.py43 lines
1# Full working Python code
2import math
3from functools import reduce
4
5def gcd(a, b):
6    while b:
7        a, b = b, a % b
8    return a
9
10def lcm(a, b):
11    return abs(a * b) // gcd(a, b)
12
13def maxFactorScore(nums):
14    n = len(nums)
15    if n == 1:
16        return nums[0] * nums[0]
17    prefix_gcd = [0] * n
18    prefix_lcm = [0] * n
19    suffix_gcd = [0] * n
20    suffix_lcm = [0] * n
21
22    prefix_gcd[0] = nums[0]
23    prefix_lcm[0] = nums[0]
24    for i in range(1, n):
25        prefix_gcd[i] = gcd(prefix_gcd[i-1], nums[i])
26        prefix_lcm[i] = lcm(prefix_lcm[i-1], nums[i])
27
28    suffix_gcd[n-1] = nums[n-1]
29    suffix_lcm[n-1] = nums[n-1]
30    for i in range(n-2, -1, -1):
31        suffix_gcd[i] = gcd(suffix_gcd[i+1], nums[i])
32        suffix_lcm[i] = lcm(suffix_lcm[i+1], nums[i])
33
34    max_score = 0
35    for i in range(n):
36        current_gcd = prefix_gcd[i-1] if i > 0 else suffix_gcd[i+1]
37        current_lcm = prefix_lcm[i-1] if i > 0 else suffix_lcm[i+1]
38        if i > 0 and i < n - 1:
39            current_gcd = gcd(prefix_gcd[i-1], suffix_gcd[i+1])
40            current_lcm = lcm(prefix_lcm[i-1], suffix_lcm[i+1])
41        max_score = max(max_score, current_gcd * current_lcm)
42    return max_score
43

Complexity note: The time complexity is O(n) because we compute GCD and LCM in linear time using prefix and suffix arrays. The space complexity is also O(n) due to the storage of these arrays.

  • 1Using prefix and suffix arrays can significantly reduce the number of calculations needed.
  • 2Understanding GCD and LCM properties is crucial for optimizing the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.