Maximum GCD-Sum of a Subarray
<p>You are given an array of integers <code>nums</code> and an integer <code>k</code>.</p>

<p>The <strong>gcd-sum</strong> of an array <code>a</code> is calculated as follows:</p>

<ul>
	<li>Let <code>s</code> be the sum of all the elements of <code>a</code>.</li>
	<li>Let <code>g</code> be the <strong>greatest common divisor</strong> of all the elements of <code>a</code>.</li>
	<li>The gcd-sum of <code>a</code> is equal to <code>s * g</code>.</li>
</ul>

<p>Return <em>the <strong>maximum gcd-sum</strong> of a subarray of</em> <code>nums</code> <em>with at least</em> <code>k</code> <em>elements.</em></p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [2,1,4,4,4,2], k = 2
<strong>Output:</strong> 48
<strong>Explanation:</strong> We take the subarray [4,4,4], the gcd-sum of this array is 4 * (4 + 4 + 4) = 48.
It can be shown that we can not select any other subarray with a gcd-sum greater than 48.</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [7,3,9,4], k = 1
<strong>Output:</strong> 81
<strong>Explanation:</strong> We take the subarray [9], the gcd-sum of this array is 9 * 9 = 81.
It can be shown that we can not select any other subarray with a gcd-sum greater than 81.</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == nums.length</code></li>
	<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>
	<li><code>1 &lt;= k &lt;= n</code></li>
</ul>
Array; Math; Binary Search; Number Theory
func maxGcdSum(nums []int, k int) int64 {
	n := len(nums)
	s := make([]int64, n+1)
	s[0] = 0
	for i, x := range nums {
		s[i+1] = s[i] + int64(x)
	}
	type pair [2]int
	var f []pair
	var ans int64
	for i := 0; i < n; i++ {
		var g []pair
		for _, p := range f {
			j, x := p[0], p[1]
			y := int(gcd(int(x), nums[i]))
			if len(g) == 0 || g[len(g)-1][1] != y {
				g = append(g, pair{j, y})
			}
		}
		f = g
		f = append(f, pair{i, nums[i]})
		for _, p := range f {
			j, x := p[0], p[1]
			if i-j+1 >= k {
				ans = max(ans, (s[i+1]-s[j])*int64(x))
			}
		}
	}
	return ans
}

func gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}