Longest subarray forming an Arithmetic Progression (AP)

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: 3
Explanation:The longest subarray forming an AP is {3, 4, 5} with common difference 1.
Input: {10, 7, 4, 6, 8, 10, 11}
Output: 4
Explanation: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: 

  1. Initialize variable res to store the length of the longest subarray forming an AP.
  2. Iterate over remaining arrays and compare the current adjacent difference with the previous adjacent difference.
  3. 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.
  4. 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.
  5. Finally, return the res as the required answer.

Below is the implementation of the above approach:
 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the length
// of longest subarray forming an AP
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 = 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 Code
int main()
{
    int arr[] = { 10, 7, 4, 6, 8, 10, 11 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << getMaxLength(arr, N);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to return the length
// of longest subarray forming an AP
static 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 Code
public 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# python3 Program to implement
# the above approach
 
# Function to return the length
# of longest subarray forming an AP
def 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 Code
if __name__ == "__main__":
    arr = [10, 7, 4, 6, 8, 10, 11]
    N = len(arr)
    print(getMaxLength(arr, N))
 
# This code is contributed by Chitranayal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to implement
// the above approach
using System;
 
public class GFG{
 
// Function to return the length
// of longest subarray forming an AP
static 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 Code
public 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

chevron_right


Output: 

4







 

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.