Longest subarray forming an Arithmetic Progression ( AP ) | Function to return the length of longest subarray forming an AP ; Minimum possible length of required subarray is 2 ; Stores the length of the current subarray ; Stores the common difference of the current AP ; Stores the common difference of the previous AP ; If the common differences are found to be equal ; Continue the previous subarray ; Start a new subarray ; Update the length to store maximum length ; Update the length to store maximum length ; Return the length of the longest subarray ; Driver Code
function getMaxLength ( arr , N ) { let res = 2 ; let dist = 2 ; let curradj = ( arr [ 1 ] - arr [ 0 ] ) ; let prevadj = ( arr [ 1 ] - arr [ 0 ] ) ; for ( let i = 2 ; i < N ; i ++ ) { curradj = arr [ i ] - arr [ i - 1 ] ; if ( curradj == prevadj ) { dist ++ ; } else { prevadj = curradj ; res = Math . max ( res , dist ) ; dist = 2 ; } } res = Math . max ( res , dist ) ; return res ; } let arr = [ 10 , 7 , 4 , 6 , 8 , 10 , 11 ] ; let N = arr . length ; document . write ( getMaxLength ( arr , N ) ) ;