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: 16
💡 Note: Double the element 8 to get [4,6,16]. The subarray [16] has GCD=16 and length=1, giving score 1×16=16, which is the maximum possible.
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 Score INPUT Array: nums 4 idx 0 6 idx 1 8 idx 2 Input Values: nums = [4, 6, 8] k = 1 (max operations) Score Formula: length × GCD(subarray) Each element doubled at most once ALGORITHM STEPS 1 Enumerate Subarrays Try all contiguous subarrays 2 Greedy Doubling Double elements to maximize GCD 3 Calculate Score Score = len × GCD 4 Track Maximum Keep best score found Subarray Analysis: [4] GCD=4 1×4=4 [6] GCD=6 1×6=6 [8] GCD=8 1×8=8 [4,6] GCD=2 2×2=4 [6,8] GCD=2 2×2=4 [4,6,8] GCD=2 3×2=6 FINAL RESULT Best Subarray Found: [8] Score Calculation: Length = 1 GCD([8]) = 8 Score = 1 × 8 = 8 OUTPUT 8 OK - Maximum Score Key Insight: For this example, doubling doesn't help increase the maximum score. The single element [8] gives the best score of 8. Doubling 4 to 8 would give [8,6,8] with GCD still 2, yielding 3×2=6. TutorialsPoint - Maximize Subarray GCD Score | Enumerate Subarrays with Greedy 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