Longest subarray forming an Arithmetic Progression ( AP ) | C ++ Program to implement the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMaxLength ( int arr [ ] , int N ) { int res = 2 ; int dist = 2 ; int curradj = ( arr [ 1 ] - arr [ 0 ] ) ; int prevadj = ( arr [ 1 ] - arr [ 0 ] ) ; for ( int i = 2 ; i < N ; i ++ ) { curradj = arr [ i ] - arr [ i - 1 ] ; if ( curradj == prevadj ) { dist ++ ; } else { prevadj = curradj ; res = max ( res , dist ) ; dist = 2 ; } } res = max ( res , dist ) ; return res ; } int main ( ) { int arr [ ] = { 10 , 7 , 4 , 6 , 8 , 10 , 11 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getMaxLength ( arr , N ) ; }