A subarray is arithmetic if the difference between consecutive elements in the subarray is constant.
You can replace at most one element in nums with any integer. Then, you select an arithmetic subarray from nums.
Return an integer denoting the maximum length of the arithmetic subarray you can select.
Β
Example 1:
Input:nums = [9,7,5,10,1]
Output:5
Explanation:
Replace nums[3] = 10 with 3. The array becomes [9, 7, 5, 3, 1].
Select the subarray [9, 7, 5, 3, 1], which is arithmetic because consecutive elements have a common difference of -2.
Example 2:
Input:nums = [1,2,6,7]
Output:3
Explanation:
Replace nums[0] = 1 with -2. The array becomes [-2, 2, 6, 7].
Select the subarray [-2, 2, 6, 7], which is arithmetic because consecutive elements have a common difference of 4.
Β
Constraints:
4 <= nums.length <= 105
1 <= nums[i] <= 105
Solutions
Solution 1: Prefix and Suffix Decomposition + Enumeration
We first compute the differences between adjacent elements of the array, stored as array \(d\), where \(d[i] = nums[i] - nums[i - 1]\).
Next, we define two arrays \(f\) and \(g\), where \(f[i]\) represents the length of the longest arithmetic subarray ending at the \(i\)-th element, and \(g[i]\) represents the length of the longest arithmetic subarray starting at the \(i\)-th element. Initially, \(f[0] = 1\), \(g[n - 1] = 1\), and all other elements are initialized to \(2\).
We can compute the values of \(f\) and \(g\) in a single pass:
For \(f\): if \(d[i] == d[i - 1]\), then \(f[i] = f[i - 1] + 1\).
For \(g\): if \(d[i + 1] == d[i + 2]\), then \(g[i] = g[i + 1] + 1\).
Then we initialize the answer to \(3\), since we can always form an arithmetic subarray of length \(3\) by replacing one element. We then enumerate each element and try to replace it with a suitable value to form a longer arithmetic subarray:
For each element \(i\), we can directly use \(f[i]\) or \(g[i]\) to update the answer.
If \(i > 0\), we can replace \(nums[i]\) with \(nums[i - 1] + d[i - 1]\) to extend the arithmetic subarray ending at \(i - 1\), updating the answer to \(f[i - 1] + 1\).
If \(i + 1 < n\), we can replace \(nums[i]\) with \(nums[i + 1] - d[i + 1]\) to extend the arithmetic subarray starting at \(i + 1\), updating the answer to \(g[i + 1] + 1\).
If \(0 < i < n - 1\), we can replace \(nums[i]\) with \(nums[i - 1] + \frac{nums[i + 1] - nums[i - 1]}{2}\) to try to bridge \(f[i - 1]\) and \(g[i + 1]\). If this value is an integer and matches both \(d[i - 1]\) and \(d[i + 1]\), we update the answer to \(3 + (f[i - 1] - 1) + (g[i + 1] - 1)\).
Finally, return the answer.
The time complexity is \(O(n)\) and the space complexity is \(O(n)\), where \(n\) is the length of the array \(nums\).