#3574

Maximize Subarray GCD Score

Hard
ArrayMathEnumerationNumber TheoryHash MapArray
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)

Instead of checking all subarrays, we can focus on the GCD of elements and their factors, leveraging the doubling operation strategically to maximize the score.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the frequency of each number and its GCD contributions.
  2. 2Step 2: For each unique number, calculate the potential score by considering how many times we can double it up to k times.
  3. 3Step 3: Update the maximum score based on the calculated contributions.
solution.py13 lines
1from collections import Counter
2import math
3
4def maxGcdScore(nums, k):
5    freq = Counter(nums)
6    max_score = 0
7    for num in freq:
8        length = freq[num]
9        score = length * num
10        if k > 0:
11            score += length * (num * 2)
12        max_score = max(max_score, score)
13    return max_score

Complexity note: We only traverse the array and use a map for counting, leading to linear complexity.

  • 1Doubling elements can significantly increase the GCD.
  • 2Maximizing length and GCD together is crucial.

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