Longest subarray forming an Arithmetic Progression (AP)

27 Dec, 2021
Given an array arr[] of size, N, the task is to find the length of the longest subarray that forms an Arithmetic Progression.Examples:
Input: arr[] = {3, 4, 5}Output: 3Explanation:The longest subarray forming an AP is {3, 4, 5} with common difference 1.Input: {10, 7, 4, 6, 8, 10, 11}Output: 4Explanation:The longest possible subarray forming an AP is {4, 6, 8, 10} with common difference(= 2).
Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays and for each subarray, check if the difference between adjacent elements remains the same throughout or not. Among all such subarrays satisfying the condition, store the length of the longest subarray and print it as the result. Time Complexity: O(N3) Auxiliary Space: O(1) 
Efficient Approach: To optimize the above approach, the idea here is to observe that whenever the difference between the current pair of adjacent elements is not equal to the difference between the previous pair of adjacent elements, compare the length of the previous subarray with the maximum obtained so far and start a new subarray and repeat accordingly. Follow the below steps to solve the problem: 
Initialize variable res to store the length of the longest subarray forming an AP.Iterate over remaining arrays and compare the current adjacent difference with the previous adjacent difference.Iterate over the array, and for each element, calculate the difference between the current pair of adjacent elements and check if it is equal to the previous pair of adjacent elements. If found to be true, continue the ongoing subarray by incrementing res by 1.Otherwise, consider a new subarray. Update the maximum length obtained so far, i.e. res by comparing it with the length of the previous subarray.Finally, return the res as the required answer.
Initialize variable res to store the length of the longest subarray forming an AP.
Iterate over remaining arrays and compare the current adjacent difference with the previous adjacent difference.
Iterate over the array, and for each element, calculate the difference between the current pair of adjacent elements and check if it is equal to the previous pair of adjacent elements. If found to be true, continue the ongoing subarray by incrementing res by 1.
Otherwise, consider a new subarray. Update the maximum length obtained so far, i.e. res by comparing it with the length of the previous subarray.
Finally, return the res as the required answer.
Below is the implementation of the above approach: 
C++14
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to return the length// of longest subarray forming an APint getMaxLength(int arr[], int N){    //single number is also an AP    //with common difference as 0    if(N==1)    return 1;     // Minimum possible length of    // required subarray is 2    int res = 2;     // Stores the length of the    // current subarray    int dist = 2;     // Stores the common difference    // of the current AP    int curradj = (arr[1] - arr[0]);     // Stores the common difference    // of the previous AP    int prevadj = (arr[1] - arr[0]);    for (int i = 2; i < N; i++) {        curradj = arr[i] - arr[i - 1];         // If the common differences        // are found to be equal        if (curradj == prevadj) {             // Continue the previous subarray            dist++;        }         // Start a new subarray        else {            prevadj = curradj;             // Update the length to            // store maximum length            res = max(res, dist);            dist = 2;        }    }     // Update the length to    // store maximum length    res = max(res, dist);     // Return the length of    // the longest subarray    return res;} // Driver Codeint main(){    int arr[] = {10, 7, 4, 6, 8, 10, 11};    int N = sizeof(arr) / sizeof(arr[0]);    cout << getMaxLength(arr, N);}
// Java Program to implement// the above approachimport java.util.*;class GFG{ // Function to return the length// of longest subarray forming an APstatic int getMaxLength(int arr[], int N){     // Minimum possible length of    // required subarray is 2    int res = 2;     // Stores the length of the    // current subarray    int dist = 2;     // Stores the common difference    // of the current AP    int curradj = (arr[1] - arr[0]);     // Stores the common difference    // of the previous AP    int prevadj = (arr[1] - arr[0]);    for (int i = 2; i < N; i++)    {        curradj = arr[i] - arr[i - 1];         // If the common differences        // are found to be equal        if (curradj == prevadj)        {            // Continue the previous subarray            dist++;        }         // Start a new subarray        else        {            prevadj = curradj;             // Update the length to            // store maximum length            res = Math.max(res, dist);            dist = 2;        }    }     // Update the length to    // store maximum length    res = Math.max(res, dist);     // Return the length of    // the longest subarray    return res;} // Driver Codepublic static void main(String[] args){    int arr[] = {10, 7, 4,                 6, 8, 10, 11};    int N = arr.length;    System.out.print(getMaxLength(arr, N));}} // This code is contributed by shikhasingrajput
# python3 Program to implement# the above approach # Function to return the length# of longest subarray forming an APdef getMaxLength(arr,  N):     # Minimum possible length of    # required subarray is 2    res = 2     # Stores the length of the    # current subarray    dist = 2     # Stores the common difference    # of the current AP    curradj = (arr[1] - arr[0])     # Stores the common difference    # of the previous AP    prevadj = (arr[1] - arr[0])    for i in range(2, N):        curradj = arr[i] - arr[i - 1]         # If the common differences        # are found to be equal        if (curradj == prevadj):             # Continue the previous subarray            dist += 1         # Start a new subarray        else:            prevadj = curradj             # Update the length to            # store maximum length            res = max(res, dist)            dist = 2     # Update the length to    # store maximum length    res = max(res, dist)     # Return the length of    # the longest subarray    return res # Driver Codeif __name__ == "__main__":    arr = [10, 7, 4, 6, 8, 10, 11]    N = len(arr)    print(getMaxLength(arr, N)) # This code is contributed by Chitranayal
// C# Program to implement// the above approachusing System; public class GFG{ // Function to return the length// of longest subarray forming an APstatic int getMaxLength(int []arr,                        int N){     // Minimum possible length of    // required subarray is 2    int res = 2;     // Stores the length of the    // current subarray    int dist = 2;     // Stores the common difference    // of the current AP    int curradj = (arr[1] - arr[0]);     // Stores the common difference    // of the previous AP    int prevadj = (arr[1] - arr[0]);       for (int i = 2; i < N; i++)    {        curradj = arr[i] - arr[i - 1];         // If the common differences        // are found to be equal        if (curradj == prevadj)        {            // Continue the previous subarray            dist++;        }         // Start a new subarray        else        {            prevadj = curradj;             // Update the length to            // store maximum length            res = Math.Max(res, dist);            dist = 2;        }    }     // Update the length to    // store maximum length    res = Math.Max(res, dist);     // Return the length of    // the longest subarray    return res;} // Driver Codepublic static void Main(String[] args){    int []arr = {10, 7, 4,                 6, 8, 10, 11};    int N = arr.Length;    Console.Write(getMaxLength(arr, N));}} // This code is contributed by 29AjayKumar
<script> // Javascript Program to implement// the above approach // Function to return the length// of longest subarray forming an APfunction getMaxLength(arr, N){     // Minimum possible length of    // required subarray is 2    let res = 2;     // Stores the length of the    // current subarray    let dist = 2;     // Stores the common difference    // of the current AP    let curradj = (arr[1] - arr[0]);     // Stores the common difference    // of the previous AP    let prevadj = (arr[1] - arr[0]);    for (let i = 2; i < N; i++) {        curradj = arr[i] - arr[i - 1];         // If the common differences        // are found to be equal        if (curradj == prevadj) {             // Continue the previous subarray            dist++;        }         // Start a new subarray        else {            prevadj = curradj;             // Update the length to            // store maximum length            res = Math.max(res, dist);            dist = 2;        }    }     // Update the length to    // store maximum length    res = Math.max(res, dist);     // Return the length of    // the longest subarray    return res;} // Driver Code     let arr= [ 10, 7, 4, 6, 8, 10, 11 ];    let N = arr.length;    document.write(getMaxLength(arr, N)); // This code is contributed by Mayank Tyagi </script>
4
 
Time Complexity: O(N)Auxiliary Space: O(1)
ukasp
shikhasingrajput
29AjayKumar
mayanktyagi1709
prophet1999
arithmetic progression
subarray
Arrays
Mathematical
Searching
Arrays
Searching
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Multidimensional Arrays in Java
Introduction to Arrays
Count of subarrays with average K
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string