Maximize Subarray GCD Score - Problem

You are given an array of positive integers nums and an integer k. You may perform at most k operations. In each operation, you can choose one element in the array and double its value. Each element can be doubled at most once.

The score of a contiguous subarray is defined as the product of its length and the greatest common divisor (GCD) of all its elements.

Your task is to return the maximum score that can be achieved by selecting a contiguous subarray from the modified array.

Note: The greatest common divisor (GCD) of an array is the largest integer that evenly divides all the array elements.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,6,8], k = 1
Output: 8
💡 Note: Double the element 8 to get [4,6,16]. The subarray [16] has GCD=16 and length=1, giving score 1×16=16. However, the subarray [4,6,8] originally has GCD=2 and length=3, score=6. After doubling 8: [4,6,16] has GCD=2, score=6. Best is subarray [8] doubled to [16] with score=16. Wait, let me recalculate: if we double 4→8, subarray [8,6,8] has GCD=2, score=6. Actually the subarray [8] alone (after doubling 8→16) gives score=16, which is maximum.
Example 2 — Multiple Operations
$ Input: nums = [2,4,6], k = 2
Output: 12
💡 Note: Double elements at indices 0 and 1: [2,4,6] → [4,8,6]. The subarray [4,8] has GCD=4 and length=2, giving score 2×4=8. The subarray [4,8,6] has GCD=2 and length=3, giving score 3×2=6. Better: double 2→4 and 6→12: [4,4,12] subarray [4,4] has GCD=4, score=8. Actually [4] alone has score=4. Check [4,4,12]: GCD=4, but wait GCD([4,4,12])=4, score=12.
Example 3 — No Operations Needed
$ Input: nums = [12,12,12], k = 0
Output: 36
💡 Note: No doubling allowed. The entire array [12,12,12] has GCD=12 and length=3, giving score 3×12=36.

Constraints

  • 1 ≤ nums.length ≤ 10
  • 1 ≤ nums[i] ≤ 100
  • 0 ≤ k ≤ nums.length

Visualization

Tap to expand
Maximize Subarray GCD Score468Original: [4,6,8], k=116Double 8 → 16Subarray [4,6,8]: GCD=2, Score=3×2=6Subarray [16]: GCD=16, Score=1×16=16Try all subarrays, optimize doubling per subarrayMaximum Score = 16Score = Length × GCD
Understanding the Visualization
1
Input
Array [4,6,8] with k=1 doubling operation
2
Process
Try doubling each element and find best subarray
3
Output
Maximum score = 16 from subarray [16]
Key Takeaway
🎯 Key Insight: Focus on individual subarrays and greedily optimize their GCD through strategic doubling
Asked in
Google 25 Amazon 18 Microsoft 15
12.5K Views
Medium Frequency
~35 min Avg. Time
420 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