Find the Maximum Factor Score of Array - Problem

You are given an integer array nums. The factor score of an array is defined as the product of the LCM (Least Common Multiple) and GCD (Greatest Common Divisor) of all elements of that array.

Return the maximum factor score of nums after removing at most one element from it.

Note:

  • Both the LCM and GCD of a single number are the number itself
  • The factor score of an empty array is 0

Input & Output

Example 1 — Powers of 2
$ Input: nums = [2,4,8,16]
Output: 64
💡 Note: Removing the first element (2) gives us [4,8,16]. GCD(4,8,16) = 4, LCM(4,8,16) = 16, so factor score = 4 × 16 = 64. This is the maximum possible.
Example 2 — Small Array
$ Input: nums = [1,2]
Output: 4
💡 Note: Original array: GCD(1,2) = 1, LCM(1,2) = 2, score = 2. Remove 1: [2] gives score = 2×2 = 4. Remove 2: [1] gives score = 1×1 = 1. Maximum is 4.
Example 3 — Single Element
$ Input: nums = [3]
Output: 9
💡 Note: Single element: GCD(3) = 3, LCM(3) = 3, factor score = 3 × 3 = 9. Removing the element gives an empty array with score 0. Maximum is 9.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Maximum Factor Score of Array INPUT nums array: 2 i=0 4 i=1 8 i=2 16 i=3 Factor Score Formula: Score = LCM * GCD Full array [2,4,8,16]: GCD = 2, LCM = 16 Score = 16 * 2 = 32 Goal: Remove at most 1 element to maximize factor score ALGORITHM STEPS 1 Build Prefix Arrays prefixGCD[i], prefixLCM[i] 2 Build Suffix Arrays suffixGCD[i], suffixLCM[i] 3 Try Each Removal Combine prefix + suffix 4 Track Maximum Compare all scores Removal Analysis: Remove 2: [4,8,16] GCD=4, LCM=16, Score=64 Remove 4: [2,8,16] GCD=2, LCM=16, Score=32 Remove 8: [2,4,16] GCD=2, LCM=16, Score=32 Remove 16: [2,4,8] GCD=2, LCM=8, Score=16 FINAL RESULT Best strategy: Remove element at index 0 Resulting array: 4 8 16 GCD(4, 8, 16) = 4 LCM(4, 8, 16) = 16 Score = 4 * 16 = 64 OUTPUT 64 OK - Maximum Found! Key Insight: Prefix/Suffix arrays let us compute GCD and LCM of any subarray excluding one element in O(1) time. For index i: combine prefix[i-1] with suffix[i+1] to get values excluding nums[i]. Total complexity: O(n) preprocessing + O(n) iteration = O(n) overall. Much better than O(n^2) brute force! TutorialsPoint - Find the Maximum Factor Score of Array | Optimized with Prefix/Suffix Arrays
Asked in
Google 35 Meta 28 Microsoft 22 Amazon 18
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen