Before solving this problem, let us solve a different problem first.
How to find if a sorted array contains an arithmetic progression of length 3?
This can be done by looping over the array and then finding numbers ‘i’ and ‘k’ on either side of current number ‘j’ such that
arr[j] + arr[k] = 2*arr[i] and
k < i < j
To find the longest AP efficiently, we can use dynamic programming (DP). We’ll use a 2D DP table where dp[i][j] represents the length of the longest AP ending with elements at indices i and j. The idea is to iterate over all pairs (i, j) where i < j, and for each pair, we look for the previous element in the AP (2*a[i] - a[j]). If such an element exists, we update the DP table accordingly.
deflongest_arith_seq_length(arr):
n = len(arr)
if n <=2:
return n
dp = [{} for _ in range(n)]
max_len =2for j in range(n):
for i in range(j):
diff = arr[j] - arr[i]
if diff in dp[i]:
dp[j][diff] = dp[i][diff] +1else:
dp[j][diff] =2 max_len = max(max_len, dp[j][diff])
return max_len
# Example usagearr1 = [1, 7, 10, 13, 14, 19]
print(f"Longest AP length in {arr1} is: {longest_arith_seq_length(arr1)}") # Output: 4 (i.e., [1, 7, 13, 19])arr2 = [1, 3, 5, 7, 9]
print(f"Longest AP length in {arr2} is: {longest_arith_seq_length(arr2)}") # Output: 5 (i.e., [1, 3, 5, 7, 9])