Longest Arithmetic Sequence After Changing At Most One Element Problem
Description
LeetCode Problem 3872.
You are given an integer array nums.
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 <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Prefix and Suffix Runs
Let d[i] = nums[i] - nums[i - 1]. Let f[i] be the length of the longest arithmetic subarray ending at i and g[i] the longest one starting at i; both start at 2 (1 at the array ends) and grow by one when two adjacent differences are equal.
Any three elements can be made arithmetic by one change, so the answer is at least 3. Then try every index i as the changed element:
- keep it:
f[i]andg[i]themselves; - rewrite
nums[i]to extend the run ending ati - 1:f[i - 1] + 1; - rewrite
nums[i]to extend the run starting ati + 1:g[i + 1] + 1; - rewrite it to the midpoint of its neighbours (only if the sum of the neighbours is even) to join the run before and the run after: if the half-difference equals the difference inside the run before (or the run after), that run is joined, so the length is
3, plusf[i - 1] - 1when the left run matches, plusg[i + 1] - 1when the right run matches.
Take the maximum.
Complexity: O(n) time and O(n) space.
class Solution:
def longestArithmetic(self, nums: List[int]) -> int:
n = len(nums)
d = [0] * n
for i in range(1, n):
d[i] = nums[i] - nums[i - 1]
f = [2] * n
g = [2] * n
f[0] = g[n - 1] = 1
for i in range(2, n):
if d[i] == d[i - 1]:
f[i] = f[i - 1] + 1
for i in range(n - 3, -1, -1):
if d[i + 1] == d[i + 2]:
g[i] = g[i + 1] + 1
ans = 3
for i in range(n):
ans = max(ans, f[i], g[i])
if i > 0:
ans = max(ans, f[i - 1] + 1)
if i + 1 < n:
ans = max(ans, g[i + 1] + 1)
if 0 < i < n - 1:
diff = nums[i + 1] - nums[i - 1]
if diff % 2 == 0:
diff //= 2
k = 3
if i > 1 and diff == d[i - 1]:
k += f[i - 1] - 1
if i < n - 2 and diff == d[i + 2]:
k += g[i + 1] - 1
ans = max(ans, k)
return ans