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
def getMaxLength ( arr , N ) : NEW_LINE INDENT res = 2 NEW_LINE dist = 2 NEW_LINE curradj = ( arr [ 1 ] - arr [ 0 ] ) NEW_LINE prevadj = ( arr [ 1 ] - arr [ 0 ] ) NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT curradj = arr [ i ] - arr [ i - 1 ] NEW_LINE if ( curradj == prevadj ) : NEW_LINE INDENT dist += 1 NEW_LINE DEDENT else : NEW_LINE INDENT prevadj = curradj NEW_LINE res = max ( res , dist ) NEW_LINE dist = 2 NEW_LINE DEDENT DEDENT res = max ( res , dist ) NEW_LINE return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 7 , 4 , 6 , 8 , 10 , 11 ] NEW_LINE N = len ( arr ) NEW_LINE print ( getMaxLength ( arr , N ) ) NEW_LINE DEDENT