Longest subsequence forming an Arithmetic Progression ( AP ) | C # program for the above approach ; 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 ; Driver Code ; Given array arr [ ] ; Function call
using System ; using System . Collections . Generic ; class GFG { static int lenghtOfLongestAP ( int [ ] A , int n ) { Dictionary < int , Dictionary < int , int > > dp = new Dictionary < int , Dictionary < int , int > > ( ) ; int res = 2 ; for ( int i = 0 ; i < n ; ++ i ) { for ( int j = i + 1 ; j < n ; ++ j ) { int d = A [ j ] - A [ i ] ; if ( dp . ContainsKey ( d ) ) { if ( dp [ d ] . ContainsKey ( i ) ) { dp [ d ] [ j ] = dp [ d ] [ i ] + 1 ; } else { dp [ d ] [ j ] = 2 ; } } else { dp [ d ] = new Dictionary < int , int > ( ) ; dp [ d ] [ j ] = 2 ; } res = Math . Max ( res , dp [ d ] [ j ] ) ; } } return res ; } public static void Main ( string [ ] args ) { int [ ] arr = { 20 , 1 , 15 , 3 , 10 , 5 , 8 } ; int N = arr . Length ; Console . Write ( lenghtOfLongestAP ( arr , N ) ) ; } }