Longest subsequence forming an Arithmetic Progression ( AP ) | Java 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
import java . io . * ; import java . util . * ; class GFG { static int lenghtOfLongestAP ( int A [ ] , int n ) { Map < Integer , Map < Integer , Integer > > dp = new HashMap < Integer , Map < Integer , Integer > > ( ) ; int res = 2 ; for ( int i = 0 ; i < n ; ++ i ) { for ( int j = i + 1 ; j < n ; ++ j ) { int d = A [ j ] - A [ i ] ; Map < Integer , Integer > temp ; if ( dp . containsKey ( d ) ) { temp = dp . get ( d ) ; if ( temp . containsKey ( i ) ) temp . put ( j , temp . get ( i ) + 1 ) ; else temp . put ( j , 2 ) ; } else { temp = new HashMap < Integer , Integer > ( ) ; temp . put ( j , 2 ) ; } dp . put ( d , temp ) ; res = Math . max ( res , temp . get ( j ) ) ; } } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 20 , 1 , 15 , 3 , 10 , 5 , 8 } ; int N = arr . length ; System . out . println ( lenghtOfLongestAP ( arr , N ) ) ; } }