
Sponsored
Sponsored
This approach involves using a 2D dynamic programming array to keep track of the lengths of arithmetic subsequences ending at different indices with various common differences. The outer loop iterates over end indices while the inner loop considers all pairs of start and end indices to update the subsequence lengths.
Time Complexity: O(n^2)
Space Complexity: O(n^2), where n is the size of the input array.
1def longestArithSeqLength(nums):
2 if len(nums) <= 2:
3 return len(nums)
4 dp = [{} for _ in range(len(nums))]
5 max_length = 2
6 for i in range(len(nums)):
7 for j in range(i):
8 diff = nums[i] - nums[j]
9 if diff in dp[j]:
10 dp[i][diff] = dp[j][diff] + 1
11 else:
12 dp[i][diff] = 2
13 max_length = max(max_length, dp[i][diff])
14 return max_length
15
16# Example usage
17nums = [3, 6, 9, 12]
18print(longestArithSeqLength(nums))The Python implementation utilizes a list of dictionaries to manage the lengths of arithmetic subsequences for each index and their respective differences. For every element `nums[i]`, it examines all preceding elements `nums[j]`, calculates the difference, and attempts to extend existing sequences.
This approach uses a simplified dynamic programming technique with HashMaps and tracks differences and their counts for each number. By leveraging HashMap structures, we manage subsequence lengths more efficiently and avoid using unnecessary space for non-existent differences.
Time Complexity: O(n^2)
Space Complexity: O(n^2) in the worst case but often much less due to sparse differences.
1
JavaScript provides a succinct implementation of the solution using built-in Maps, iterating through pairs of indices and managing difference-based sequence length efficiently in terms of both computation and space.