Longest Arithmetic Progression
Given an array Set[ ] of sorted integers having no duplicates, find the length of the Longest Arithmetic Progression (LLAP) subsequence in it.
Examples:Â
Input: Set[] = {1, 7, 10, 15, 27, 29}
Output: 3
Explanation: The longest arithmetic progression is {1, 15, 29} having common difference 14.
Input: Set[] = {5, 10, 15, 20, 25, 30}
Output: 6
Explanation: The whole set is in AP having common difference 5.
Approach 1: Brute forcing the solution in O(N^3)
A simple solution is to one by one consider every pair as first two elements of AP and check for the remaining elements in sorted array. To consider all pairs as first two elements, we need to run a O(n^2) nested loop. Inside the nested loops, we need a third loop which linearly looks for the more elements in Arithmetic Progression (AP). This process takes O(n3) time.Â
We can solve this problem in O(n2) time using Dynamic Programming. To get idea of the DP solution, let us first discuss solution of following simpler problem.
Given a sorted Array, find if there exist three elements in Arithmetic Progression or not:Â
Please note that, the answer is true if there are 3 or more elements in AP, otherwise false. To find the three elements, we first fix an element as middle element and search for other two (one smaller and one greater). We start from the second element and fix every element as middle element.
For an element set[j] to be middle of AP, there must exist elements ‘set[i]’ and ‘set[k]’ such that set[i] + set[k] = 2*set[j] where 0 <= i < j and j < k <=n-1.Â
Algorithm to efficiently find i and k for a given j:Â
We can find i and k in linear time using following simple algorithm.Â
- Initialize i as j-1 and k as j+1
- Do following while i >= 0 and k <= n-1
- If set[i] + set[k] is equal to 2*set[j], then we are done.
- If set[i] + set[k] > 2*set[j], then decrement i (do i–).
- Else if set[i] + set[k] < 2*set[j], then increment k (do k++).
Following is the implementation of the above algorithm for the simpler problem. Â
C++
bool arithmeticThree(vector< int > set, int n)
{
for ( int j = 1; j < n - 1; j++)
{
int i = j - 1, k = j + 1;
while (i >= 0 && k <= n-1)
{
if (set[i] + set[k] == 2 * set[j])
return true ;
(set[i] + set[k] < 2 * set[j]) ? k++ : i--;
}
}
return false ;
}
|
C
bool arithmeticThree( int set[], int n)
{
for ( int j=1; j<n-1; j++)
{
int i = j-1, k = j+1;
while (i >= 0 && k <= n-1)
{
if (set[i] + set[k] == 2*set[j])
return true ;
(set[i] + set[k] < 2*set[j])? k++ : i--;
}
}
return false ;
}
|
Java
static boolean arithmeticThree( int set[], int n)
{
for ( int j = 1 ; j < n - 1 ; j++)
{
int i = j - 1 , k = j + 1 ;
while (i >= 0 && k <= n- 1 )
{
if (set[i] + set[k] == 2 *set[j])
return true ;
(set[i] + set[k] < 2 *set[j])? k++ : i--;
}
}
return false ;
}
|
C#
static bool arithmeticThree( int [] set , int n)
{
for ( int j = 1; j < n - 1; j++)
{
int i = j - 1, k = j + 1;
while (i >= 0 && k <= n-1)
{
if ( set [i] + set [k] == 2* set [j])
return true ;
if ( set [i] + set [k] < 2* set [j])
k++;
else
i--;
}
}
return false ;
}
|
Javascript
<script>
function arithmeticThree(set, n){
for (let j=1; j<n-1; j++)
{
let i = j-1, k = j+1;
while (i >= 0 && k <= n-1)
{
if (set[i] + set[k] == 2*set[j])
return true ;
(set[i] + set[k] < 2*set[j])? k++ : i--;
}
}
return false ;
}
</script>
|
Python3
def arithematicThree(set_,n):
for j in range (n):
i,k = j - 1 ,j + 1
while i> - 1 and k<n:
if set_[i] + set_[k] = = 2 * set_[j]:
return True
elif set_[i] + set_[k]< 2 * set_[j]:
i - = 1
else :
k + = 1
return False
|
Iteratively examining all possible pairs of elements as the first two elements of an AP and then extending the AP to find the longest one. The algorithm uses a dynamic programming approach to store the length of the LLAP ending at each pair of elements. It starts with a minimum LLAP length of 2 (two elements), and as it iterates through the elements, it updates and keeps track of the maximum LLAP length found so far. Finally, it returns the length of the longest arithmetic progression found in the set.
The below image shows how the dp table fills for the array [1, 7, 10, 13, 14, 19].
Step-by-step approach:
- Initialize a 2D array L[][] to store the length of LLAPs ending at pairs of elements.
- For each element in the set, fill the last column of L[][] with 2 since any pair forms an AP of length 2.
- Starting from the second-to-last column, iterate through pairs of elements (set[i], set[j]).
- Within the loop, compare set[i] + set[k] to 2 * set[j]:
- If less, increment k to consider a larger element.
- If greater, decrement i to consider a smaller element.
- If equal, extend the LLAP by setting L[i][j] to L[j][k] + 1 and update the maximum LLAP length (llap).
- Handle cases where k exceeds the last index by filling in remaining cells in the column with 2.
- Return the maximum LLAP length (llap) found in the set.
Following is the implementation of the Dynamic Programming algorithm.Â
C++
#include <iostream>
using namespace std;
int lenghtOfLongestAP( int set[], int n)
{
if (n <= 2) return n;
int L[n][n];
int llap = 2;
for ( int i = 0; i < n; i++)
L[i][n-1] = 2;
for ( int j=n-2; j>=1; j--)
{
int i = j-1, k = j+1;
while (i >= 0 && k <= n-1)
{
if (set[i] + set[k] < 2*set[j])
k++;
else if (set[i] + set[k] > 2*set[j])
{ L[i][j] = 2, i--; }
else
{
L[i][j] = L[j][k] + 1;
llap = max(llap, L[i][j]);
i--; k++;
}
}
while (i >= 0)
{
L[i][j] = 2;
i--;
}
}
return llap;
}
int main()
{
int set1[] = {1, 7, 10, 13, 14, 19};
int n1 = sizeof (set1)/ sizeof (set1[0]);
cout << lenghtOfLongestAP(set1, n1) << endl;
int set2[] = {1, 7, 10, 15, 27, 29};
int n2 = sizeof (set2)/ sizeof (set2[0]);
cout << lenghtOfLongestAP(set2, n2) << endl;
int set3[] = {2, 4, 6, 8, 10};
int n3 = sizeof (set3)/ sizeof (set3[0]);
cout << lenghtOfLongestAP(set3, n3) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int lenghtOfLongestAP( int set[], int n)
{
if (n <= 2 ) return n;
int L[][] = new int [n][n];
int llap = 2 ;
for ( int i = 0 ; i < n; i++)
L[i][n - 1 ] = 2 ;
for ( int j = n - 2 ; j >= 1 ; j--)
{
int i = j - 1 , k = j + 1 ;
while (i >= 0 && k <= n - 1 )
{
if (set[i] + set[k] < 2 * set[j])
k++;
else if (set[i] + set[k] > 2 * set[j])
{
L[i][j] = 2 ; i--;
}
else
{
L[i][j] = L[j][k] + 1 ;
llap = Math.max(llap, L[i][j]);
i--; k++;
}
}
while (i >= 0 )
{
L[i][j] = 2 ;
i--;
}
}
return llap;
}
public static void main (String[] args)
{
int set1[] = { 1 , 7 , 10 , 13 , 14 , 19 };
int n1 = set1.length;
System.out.println ( lenghtOfLongestAP(set1, n1));
int set2[] = { 1 , 7 , 10 , 15 , 27 , 29 };
int n2 = set2.length;
System.out.println(lenghtOfLongestAP(set2, n2));
int set3[] = { 2 , 4 , 6 , 8 , 10 };
int n3 = set3.length;
System.out.println(lenghtOfLongestAP(set3, n3)) ;
}
}
|
C#
using System;
class GFG
{
static int lenghtOfLongestAP( int [] set ,
int n)
{
if (n <= 2) return n;
int [,]L = new int [n, n];
int llap = 2;
for ( int i = 0; i < n; i++)
L[i, n - 1] = 2;
for ( int j = n - 2; j >= 1; j--)
{
int i = j - 1 , k = j + 1;
while (i >= 0 && k <= n - 1)
{
if ( set [i] + set [k] < 2 * set [j])
k++;
else if ( set [i] + set [k] > 2 * set [j])
{
L[i, j] = 2; i--;
}
else
{
L[i, j] = L[j, k] + 1;
llap = Math.Max(llap, L[i, j]);
i--; k++;
}
}
while (i >= 0)
{
L[i, j] = 2;
i--;
}
}
return llap;
}
static public void Main ()
{
int []set1 = {1, 7, 10, 13, 14, 19};
int n1 = set1.Length;
Console.WriteLine(lenghtOfLongestAP(set1, n1));
int []set2 = {1, 7, 10, 15, 27, 29};
int n2 = set2.Length;
Console.WriteLine(lenghtOfLongestAP(set2, n2));
int []set3 = {2, 4, 6, 8, 10};
int n3 = set3.Length;
Console.WriteLine(lenghtOfLongestAP(set3, n3)) ;
}
}
|
Javascript
<script>
function lenghtOfLongestAP(set,n)
{
if (n <= 2)
return n;
let L= new Array(n);
for (let i=0;i<n;i++)
{
L[i]= new Array(n);
}
let llap = 2;
for (let i = 0; i < n; i++)
{
L[i][n - 1] = 2;
}
for (let j = n - 2; j >= 1; j--)
{
let i = j -1 , k = j + 1;
while (i >= 0 && k <= n - 1)
{
if (set[i] + set[k] < 2 * set[j])
k++;
else if (set[i] + set[k] > 2 * set[j])
{
L[i][j] = 2; i--;
}
else
{
L[i][j] = L[j][k] + 1;
llap = Math.max(llap, L[i][j]);
i--; k++;
}
}
while (i >= 0)
{
L[i][j] = 2;
i--;
}
}
return llap;
}
let set1=[1, 7, 10, 13, 14, 19];
let n1 = set1.length;
document.write( lenghtOfLongestAP(set1, n1)+ "<br>" );
let set2=[1, 7, 10, 15, 27, 29];
let n2 = set2.length;
document.write( lenghtOfLongestAP(set2, n2)+ "<br>" );
let set3=[2, 4, 6, 8, 10];
let n3 = set3.length;
document.write( lenghtOfLongestAP(set3, n3)+ "<br>" );
</script>
|
PHP
<?php
function lenghtOfLongestAP( $set , $n )
{
if ( $n <= 2)
return $n ;
$L [ $n ][ $n ] = array ( array ());
$llap = 2;
for ( $i = 0; $i < $n ; $i ++)
$L [ $i ][ $n - 1] = 2;
for ( $j = $n - 2; $j >= 1; $j --)
{
$i = $j - 1;
$k = $j + 1;
while ( $i >= 0 && $k <= $n - 1)
{
if ( $set [ $i ] + $set [ $k ] < 2 * $set [ $j ])
$k ++;
else if ( $set [ $i ] + $set [ $k ] > 2 * $set [ $j ])
{
$L [ $i ][ $j ] = 2;
$i --; }
else
{
$L [ $i ][ $j ] = $L [ $j ][ $k ] + 1;
$llap = max( $llap , $L [ $i ][ $j ]);
$i --;
$k ++;
}
}
while ( $i >= 0)
{
$L [ $i ][ $j ] = 2;
$i --;
}
}
return $llap ;
}
$set1 = array (1, 7, 10, 13, 14, 19);
$n1 = sizeof( $set1 );
echo lenghtOfLongestAP( $set1 , $n1 ), "\n" ;
$set2 = array (1, 7, 10, 15, 27, 29);
$n2 = sizeof( $set2 );
echo lenghtOfLongestAP( $set2 , $n2 ), "\n" ;
$set3 = array (2, 4, 6, 8, 10);
$n3 = sizeof( $set3 );
echo lenghtOfLongestAP( $set3 , $n3 ), "\n" ;
?>
|
Python3
def lenghtOfLongestAP( set , n):
if (n < = 2 ):
return n
L = [[ 0 for x in range (n)]
for y in range (n)]
llap = 2
for i in range (n):
L[i][n - 1 ] = 2
for j in range (n - 2 , 0 , - 1 ):
i = j - 1
k = j + 1
while (i > = 0 and k < = n - 1 ):
if ( set [i] + set [k] < 2 * set [j]):
k + = 1
elif ( set [i] + set [k] > 2 * set [j]):
L[i][j] = 2
i - = 1
else :
L[i][j] = L[j][k] + 1
llap = max (llap, L[i][j])
i - = 1
k + = 1
while (i > = 0 ):
L[i][j] = 2
i - = 1
return llap
if __name__ = = "__main__" :
set1 = [ 1 , 7 , 10 , 13 , 14 , 19 ]
n1 = len (set1)
print (lenghtOfLongestAP(set1, n1))
set2 = [ 1 , 7 , 10 , 15 , 27 , 29 ]
n2 = len (set2)
print (lenghtOfLongestAP(set2, n2))
set3 = [ 2 , 4 , 6 , 8 , 10 ]
n3 = len (set3)
print (lenghtOfLongestAP(set3, n3))
|
Time Complexity: O(n2)Â
Auxiliary Space: O(n2)
Last Updated :
07 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...