This is a Java Program to implement Longest Arithmetic Progression Algorithm. This program finds the length of longest arithmetic progression from an array of numbers.

Here is the source code of the Java Program to implement Longest Arithmetic Progression Algorithm. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

`/**`

`** Java Program to implement Longest Arithmetic Progression Algorithm`

`**/`

import java.util.Scanner;

`/** Class LongestArithmeticProgression **/`

public class LongestArithmeticProgression

`{`

`/** function lap **/`

public int lap(int[] A)

`{`

int n = A.length;

if (n == 1)

return 1;

int[][] L = new int[n + 1][n + 1];

int maxLen = 2;

for (int j = n - 1; j >= 0; j--)

`{`

int i = j - 1, k = j + 1;

while (i >= 0 && k < n)

`{`

if (A[i] + A[k] < 2 * A[j])

k = k + 1;

else if (A[i] + A[k] > 2 * A[j])

`{`

L[i][j] = 2;

i = i - 1;

`}`

`else`

`{`

L[i][j] = L[j][k] + 1;

maxLen = Math.max(maxLen, L[i][j]);

i = i - 1;

k = k + 1;

`}`

`}`

while (i >= 0)

`{`

L[i][j] = 2;

i = i - 1;

`}`

`}`

return maxLen;

`}`

`/** Main Function **/`

public static void main(String[] args)

`{`

Scanner scan = new Scanner(System.in);

System.out.println("Longest Arithmetic Progression Algorithm Test\n");

System.out.println("Enter number of elements");

int n = scan.nextInt();

int[] arr = new int[n];

System.out.println("\nEnter "+ n +" elements");

for (int i = 0; i < n; i++)

arr[i] = scan.nextInt();

LongestArithmeticProgression obj = new LongestArithmeticProgression();

int result = obj.lap(arr);

`/** print result **/`

System.out.println("\nLength of Longest Arithmetic Progression : "+ result);

`}`

`}`

Longest Arithmetic Progression Algorithm Test Enter number of elements 10 Enter 10 elements 1 3 7 13 14 15 19 20 25 30 Length of Longest Arithmetic Progression : 5 Longest Arithmetic Progression Algorithm Test Enter number of elements 10 Enter 10 elements 1 2 3 4 5 6 7 8 9 10 Length of Longest Arithmetic Progression : 10

**Sanfoundry Global Education & Learning Series – 1000 Java Programs.**

If you wish to look at all Java Programming examples, go to Java Programs.

**If you liked this Java Program, kindly share, recommend or like below!**