# 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++14

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

## Java

 `// 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`

## Python3

 `# 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`

## C#

 `// 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`

## Javascript

 ``

Output:

`4`

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

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next