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
function lenghtOfLongestAP ( A , n ) { var dp = new Map ( ) ; var res = 2 ; for ( var i = 0 ; i < n ; ++ i ) { for ( var j = i + 1 ; j < n ; ++ j ) { var d = A [ j ] - A [ i ] ; if ( dp . has ( d ) ) { if ( dp . get ( d ) . has ( i ) ) { var tmp = dp . get ( d ) ; tmp . set ( j , dp . get ( d ) . get ( i ) + 1 ) ; } else { var tmp = new Map ( ) ; tmp . set ( j , 2 ) ; dp . set ( d , tmp ) ; } } else { var tmp = new Map ( ) ; tmp . set ( j , 2 ) ; dp . set ( d , tmp ) ; } res = Math . max ( res , dp . get ( d ) . get ( j ) ) ; } } return res ; } var arr = [ 20 , 1 , 15 , 3 , 10 , 5 , 8 ] ; var N = arr . length ; document . write ( lenghtOfLongestAP ( arr , N ) ) ;