Longest subsequence forming an Arithmetic Progression ( AP ) | Function that finds the longest arithmetic subsequence having the same absolute difference ; Stores the length of sequences having same difference ; Stores the resultant length ; Iterate over the array ; Update length of subsequence ; Return res ;  ; Given array arr [ ] ; Function Call
def lenghtOfLongestAP ( A , n ) : NEW_LINE INDENT dp = { } NEW_LINE res = 2 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT d = A [ j ] - A [ i ] NEW_LINE if d in dp : NEW_LINE INDENT if i in dp [ d ] : NEW_LINE INDENT dp [ d ] [ j ] = dp [ d ] [ i ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ d ] [ j ] = 2 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT dp [ d ] = { } NEW_LINE dp [ d ] [ j ] = 2 NEW_LINE DEDENT if d in dp : NEW_LINE INDENT if j in dp [ d ] : NEW_LINE INDENT res = max ( res , dp [ d ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return res NEW_LINE DEDENT / * Driver Code * / NEW_LINE arr = [ 20 , 1 , 15 , 3 , 10 , 5 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE print ( lenghtOfLongestAP ( arr , N ) ) NEW_LINE