#3872

Longest Arithmetic Sequence After Changing At Most One Element

Medium
ArrayEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use dynamic programming to track the longest arithmetic subsequence lengths while allowing one change. This reduces the need for nested loops.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create two arrays L and R to store lengths of arithmetic sequences ending and starting at each index.
  2. 2Step 2: Populate L by checking differences and counting lengths, then populate R similarly.
  3. 3Step 3: Combine L and R to find the maximum length by considering changing one element.
solution.py13 lines
1def longestArithSeqLength(nums):
2    n = len(nums)
3    L = [2] * n
4    R = [2] * n
5    for i in range(1, n):
6        for j in range(i):
7            if nums[i] - nums[j] == nums[j] - nums[j-1]:
8                L[i] = L[j] + 1
9    for i in range(n-2, -1, -1):
10        for j in range(i+1, n):
11            if nums[j] - nums[i] == nums[i+1] - nums[i]:
12                R[i] = R[j] + 1
13    return max(max(L), max(R))

Complexity note: Single pass to compute L and R arrays, leading to linear time complexity.

  • 1Changing one element can create a longer arithmetic sequence.
  • 2Dynamic programming can efficiently track subarray lengths.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.