Open In App

Longest Arithmetic Progression

Last Updated : 22 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of sorted integers and distinct positive integers, find the length of the Longest Arithmetic Progression in it.
Note: A sequence seq is an arithmetic progression if seq[i + 1] - seq[i] are all the same value (for 0 <= i < seq.length - 1).

Examples: 

Input: arr[] = [1, 7, 10, 15, 27, 29]
Output: 3
Explanation: The longest arithmetic progression is [1, 15, 29] having common difference 14.

Input: arr []= [5, 10, 15, 20, 25, 30]
Output: 6
Explanation: The whole set is in AP having common difference 5.

Using Recursion - O(n^3) Time and O(n) Space

For the recursive approach to finding the length of the longest arithmetic progression (AP), there are two main cases:

Include the current element in the AP

  • If the difference between the current element and a previous element matches the desired difference, extend the AP by considering the current element.

Mathematically: solve(i, diff) = 1 + solve(j, diff) for all j < i such that arr[i] - arr[j] = diff.

Exclude the current element from the AP:

  • Skip the current element and proceed with the remaining elements.

Mathematically: solve(i, diff) = max(solve(i - 1, diff), solve(j, diff)) where j < i.

Base Case: solve(i, diff) = 0 when i < 0. This means if there are no elements left to form an AP, the length is zero.

For every pair of indices (i, j), compute the maximum AP length as:

  • Length = max(Length, 2 + solve(i, arr[j] - arr[i]))
C++
// C++ program to find the length of the longest 
// arithmetic progression (AP) using recursion
#include <bits/stdc++.h>
using namespace std;

// Recursive function to find the length of AP 
// ending at index `index` with difference `diff`
int solve(int index, int diff, vector<int> &arr) {
  
    // Base case: if index goes out of bounds, 
    // return 0
    if (index < 0) 
        return 0;

    int ans = 0;

    for (int j = index - 1; j >= 0; j--) {
      
        // If the difference matches, extend the AP
        if (arr[index] - arr[j] == diff) {
            ans = max(ans, 1 + solve(j, diff, arr));
        }
    }

    return ans;
}

// Function to find the length of the longest 
// arithmetic progression (AP) in the array
int lengthOfLongestAP(vector<int> &arr) {
  
    int n = arr.size();

    if (n <= 2) 
        return n;

    int ans = 0;

    // Iterate through all pairs of elements as 
    // possible first two terms
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
          
            // Calculate difference and find 
            // AP using recursion
            ans = max(ans, 2 + solve(i, 
                                arr[j] - arr[i], arr));
        }
    }

    return ans;
}

int main() {

    vector<int> arr = {1, 7, 10, 15, 27, 29};

    cout << lengthOfLongestAP(arr) << endl;

    return 0;
}
Java
// Java program to find the length of the longest 
// arithmetic progression (AP) using recursion
import java.util.ArrayList;

class GfG {

    // Recursive function to find the length of AP 
    // ending at index `index` with difference `diff`
    static int solve(int index, int diff, 
                     ArrayList<Integer> arr) {

        // Base case: if index goes out of bounds, 
        // return 0
        if (index < 0) {
            return 0;
        }

        int ans = 0;

        // Iterate through previous elements 
        // to find matching differences
        for (int j = index - 1; j >= 0; j--) {

            // If the difference matches, extend the AP
            if (arr.get(index) - arr.get(j) == diff) {
                ans = Math.max(ans, 
                               1 + solve(j, diff, arr));
            }
        }

        return ans;
    }

    // Function to find the length of the longest 
    // arithmetic progression (AP) in the array
    static int lengthOfLongestAP(ArrayList<Integer> arr) {
        
        int n = arr.size();

        // If there are less than 3 elements, 
        // return the size
        if (n <= 2) {
            return n;
        }

        int ans = 0;

        // Iterate through all pairs of elements as 
        // possible first two terms
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {

                // Calculate difference and find AP 
                // using recursion
                int diff = arr.get(j) - arr.get(i);
                ans = Math.max(ans, 
                               2 + solve(i, diff, arr));
            }
        }

        return ans;
    }

    public static void main(String[] args) {

        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(7);
        arr.add(10);
        arr.add(15);
        arr.add(27);
        arr.add(29);

        System.out.println(lengthOfLongestAP(arr));
    }
}
Python
# Python program to find the length of the longest 
# arithmetic progression (AP) using recursion

# Function to find the length of AP ending at
# index `index` with difference `diff`
def solve(index, diff, arr):
    
    # Base case: if index goes out of bounds,
    # return 0
    if index < 0:
        return 0
    
    ans = 0

    # Iterate through previous elements to find
    # matching differences
    for j in range(index - 1, -1, -1):

        # If the difference matches, extend the AP
        if arr[index] - arr[j] == diff:
            ans = max(ans, 1 + solve(j, diff, arr))
    
    return ans

# Function to find the length of the longest
# arithmetic progression (AP) in the array
def lengthOfLongestAP(arr):
    
    n = len(arr)

    # If there are less than 3 elements,
    # return the size
    if n <= 2:
        return n
    
    ans = 0

    # Iterate through all pairs of elements as
    # possible first two terms
    for i in range(n):
        for j in range(i + 1, n):

            # Calculate difference and find AP
            # using recursion
            diff = arr[j] - arr[i]
            ans = max(ans, 2 + solve(i, diff, arr))
    
    return ans

if __name__ == "__main__":
  
    arr = [1, 7, 10, 15, 27, 29]

    print(lengthOfLongestAP(arr))
C#
// C# program to find the length of the longest 
// arithmetic progression (AP) using recursion
using System;
using System.Collections.Generic;

class GfG {

    // Recursive function to find the length of AP 
    // ending at index `index` with difference `diff`
    static int Solve(int index, int diff, 
                            List<int> arr) {

        // Base case: if index goes out of bounds, 
        // return 0
        if (index < 0) {
            return 0;
        }

        int ans = 0;

        // Iterate through previous elements 
        // to find matching differences
        for (int j = index - 1; j >= 0; j--) {

            // If the difference matches, extend the AP
            if (arr[index] - arr[j] == diff) {
                ans = Math.Max(ans, 
                               1 + Solve(j, diff, arr));
            }
        }

        return ans;
    }

    // Function to find the length of the longest 
    // arithmetic progression (AP) in the array
    static int LengthOfLongestAP(List<int> arr) {

        int n = arr.Count;

        // If there are less than 3 elements, 
        // return the size
        if (n <= 2) {
            return n;
        }

        int ans = 0;

        // Iterate through all pairs of elements as 
        // possible first two terms
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {

                // Calculate difference and find AP 
                // using recursion
                int diff = arr[j] - arr[i];
                ans = Math.Max(ans, 
                               2 + Solve(i, diff, arr));
            }
        }

        return ans;
    }

    static void Main(string[] args) {

        List<int> arr = new List<int> { 1, 7, 10, 
                                        15, 27, 29 };

        Console.WriteLine(LengthOfLongestAP(arr));
    }
}
JavaScript
// Javascript program to find the length of the longest 
// arithmetic progression (AP) using recursion

// Function to find the length of AP ending at 
// index `index` with difference `diff`
function solve(index, diff, arr) {

    // Base case: if index goes out of bounds, 
    // return 0
    if (index < 0) {
        return 0;
    }

    let ans = 0;

    // Iterate through previous elements to find 
    // matching differences
    for (let j = index - 1; j >= 0; j--) {

        // If the difference matches, extend the AP
        if (arr[index] - arr[j] === diff) {
            ans = Math.max(ans, 
                           1 + solve(j, diff, arr));
        }
    }

    return ans;
}

// Function to find the length of the longest 
// arithmetic progression (AP) in the array
function lengthOfLongestAP(arr) {

    const n = arr.length;

    // If there are less than 3 elements, 
    // return the size
    if (n <= 2) {
        return n;
    }

    let ans = 0;

    // Iterate through all pairs of elements as 
    // possible first two terms
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {

            // Calculate difference and find AP 
            // using recursion
            const diff = arr[j] - arr[i];
            ans = Math.max(ans, 
                           2 + solve(i, diff, arr));
        }
    }

    return ans;
}

const arr = [1, 7, 10, 15, 27, 29];
console.log(lengthOfLongestAP(arr));

Output
3

Using Top-Down DP (Memoization) - O(n^2) Time and O(n^2) Space

1. Optimal Substructure: The solution to the problem can be derived from optimal solutions of smaller subproblems. Specifically, If the difference diff between two elements matches the desired difference for an AP ending at index, we extend the progression:

  • solve(index, diff) = 1 + solve(j, diff) where j < index and arr[index] - arr[j] = diff.

If no such j exists, the result for solve(index, diff) remains the same.

2. Overlapping Subproblems: In the recursive solution, many subproblems are recomputed multiple times. For example, solve(i, diff) for a specific index and difference can be computed repeatedly for different calls in the recursion tree. Memoization stores these results to avoid redundant calculations.
If the value for solve(index, diff) is already computed and stored in memo[index][diff], it is directly returned to avoid redundant computation:

  • solve(index, diff) = memo[index][diff], if memo[index][diff] exists.
C++
// C++ program to find the length of the longest 
// arithmetic progression (AP) using recursion 
// with memoization
#include <bits/stdc++.h>
using namespace std;

// Recursive function to find the length of AP 
// ending at index `index` with difference `diff`
int solve(int index, int diff, vector<int> &arr, 
          unordered_map<int, unordered_map<int, int>> &memo) {

    // Base case: if index goes out of bounds, 
    // return 0
    if (index < 0) 
        return 0;

    // Check memo table for precomputed result
    if (memo[index].count(diff)) 
        return memo[index][diff];

    int ans = 0;

    for (int j = index - 1; j >= 0; j--) {
        
        // If the difference matches, extend the AP
        if (arr[index] - arr[j] == diff) {
            ans = max(ans, 1 + solve(j, diff, arr, memo));
        }
    }

    // Store the result in the memo table
    return memo[index][diff] = ans;
}

// Function to find the length of the longest 
// arithmetic progression (AP) in the array
int lengthOfLongestAP(vector<int> &arr) {

    int n = arr.size();

    if (n <= 2) 
        return n;

    int ans = 0;

    // Memoization table to store results for solve()
    unordered_map<int, unordered_map<int, int>> memo;

    // Iterate through all pairs of elements as 
    // possible first two terms
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {

            // Calculate difference and find 
            // AP using memoized recursion
            ans = max(ans, 2 + solve(i, 
                                arr[j] - arr[i], arr, memo));
        }
    }

    return ans;
}

int main() {

    vector<int> arr = {1, 7, 10, 15, 27, 29};

    cout << lengthOfLongestAP(arr) << endl;

    return 0;
}
Java
// Java program to find the length of the longest 
// arithmetic progression (AP) using recursion 
// with memoization
import java.util.ArrayList;
import java.util.HashMap;

class GfG {

    // Recursive function to find the length of AP 
    // ending at index `index` with difference `diff`
    static int solve(int index, int diff, 
                     ArrayList<Integer> arr, 
                     HashMap<Integer, HashMap<Integer, Integer>> memo) {

        // Base case: if index goes out of bounds, 
        // return 0
        if (index < 0) {
            return 0;
        }

        // Check memo table for precomputed result
        if (memo.containsKey(index) && 
            memo.get(index).containsKey(diff)) {
            return memo.get(index).get(diff);
        }

        int ans = 0;

        // Iterate through previous elements 
        // to find matching differences
        for (int j = index - 1; j >= 0; j--) {

            // If the difference matches, extend the AP
            if (arr.get(index) - arr.get(j) == diff) {
                ans = Math.max(ans, 
                               1 + solve(j, diff, arr, memo));
            }
        }

        // Store the result in the memo table
        memo.putIfAbsent(index, new HashMap<>());
        memo.get(index).put(diff, ans);

        return ans;
    }

    // Function to find the length of the longest 
    // arithmetic progression (AP) in the array
    static int lengthOfLongestAP(ArrayList<Integer> arr) {
        
        int n = arr.size();

        // If there are less than 3 elements, 
        // return the size
        if (n <= 2) {
            return n;
        }

        int ans = 0;

        // Memoization table to store results for solve()
        HashMap<Integer, HashMap<Integer, Integer>> memo = 
            new HashMap<>();

        // Iterate through all pairs of elements as 
        // possible first two terms
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {

                // Calculate difference and find AP 
                // using memoized recursion
                int diff = arr.get(j) - arr.get(i);
                ans = Math.max(ans, 
                               2 + solve(i, diff, arr, memo));
            }
        }

        return ans;
    }

    public static void main(String[] args) {

        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(7);
        arr.add(10);
        arr.add(15);
        arr.add(27);
        arr.add(29);

        System.out.println(lengthOfLongestAP(arr));
    }
}
Python
# Python program to find the length of the longest 
# arithmetic progression (AP) using recursion 
# with memoization

# Function to find the length of AP ending at
# index `index` with difference `diff`
def solve(index, diff, arr, memo):
    
    # Base case: if index goes out of bounds,
    # return 0
    if index < 0:
        return 0
    
    # Check if the result is already computed
    if (index, diff) in memo:
        return memo[(index, diff)]
    
    ans = 0

    # Iterate through previous elements to find
    # matching differences
    for j in range(index - 1, -1, -1):

        # If the difference matches, extend the AP
        if arr[index] - arr[j] == diff:
            ans = max(ans, 1 + solve(j, diff, arr, memo))
    
    # Store the result in the memo dictionary
    memo[(index, diff)] = ans
    return ans

# Function to find the length of the longest
# arithmetic progression (AP) in the array
def lengthOfLongestAP(arr):
    
    n = len(arr)

    # If there are less than 3 elements,
    # return the size
    if n <= 2:
        return n
    
    ans = 0

    # Memoization dictionary to store results for solve
    memo = {}

    # Iterate through all pairs of elements as
    # possible first two terms
    for i in range(n):
        for j in range(i + 1, n):

            # Calculate difference and find AP
            # using memoized recursion
            diff = arr[j] - arr[i]
            ans = max(ans, 2 + solve(i, diff, arr, memo))
    
    return ans

if __name__ == "__main__":
  
    arr = [1, 7, 10, 15, 27, 29]

    print(lengthOfLongestAP(arr))
C#
// C# program to find the length of the longest 
// arithmetic progression (AP) using recursion 
// with memoization
using System;
using System.Collections.Generic;

class GfG {

    // Recursive function to find the length of AP 
    // ending at index `index` with difference `diff`
    static int Solve(int index, int diff, 
                            List<int> arr, 
                            Dictionary<(int, int), int> memo) {

        // Base case: if index goes out of bounds, 
        // return 0
        if (index < 0) {
            return 0;
        }

        // Check if the result is already computed
        if (memo.ContainsKey((index, diff))) {
            return memo[(index, diff)];
        }

        int ans = 0;

        // Iterate through previous elements 
        // to find matching differences
        for (int j = index - 1; j >= 0; j--) {

            // If the difference matches, extend the AP
            if (arr[index] - arr[j] == diff) {
                ans = Math.Max(ans, 
                               1 + Solve(j, diff, arr, memo));
            }
        }

        // Store the result in the memo dictionary
        memo[(index, diff)] = ans;
        return ans;
    }

    // Function to find the length of the longest 
    // arithmetic progression (AP) in the array
    static int LengthOfLongestAP(List<int> arr) {

        int n = arr.Count;

        // If there are less than 3 elements, 
        // return the size
        if (n <= 2) {
            return n;
        }

        int ans = 0;

        // Memoization dictionary to store results for Solve
        var memo = new Dictionary<(int, int), int>();

        // Iterate through all pairs of elements as 
        // possible first two terms
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {

                // Calculate difference and find AP 
                // using memoized recursion
                int diff = arr[j] - arr[i];
                ans = Math.Max(ans, 
                               2 + Solve(i, diff, arr, memo));
            }
        }

        return ans;
    }

    static void Main(string[] args) {

        List<int> arr = new List<int> { 1, 7, 10, 
                                        15, 27, 29 };

        Console.WriteLine(LengthOfLongestAP(arr));
    }
}
JavaScript
// Javascript program to find the length of the longest 
// arithmetic progression (AP) using recursion with memoization

// Function to find the length of AP ending at 
// index `index` with difference `diff`
function solve(index, diff, arr, memo) {

    // Base case: if index goes out of bounds, 
    // return 0
    if (index < 0) {
        return 0;
    }

    // Check if the result is already computed
    const key = `${index}-${diff}`;
    if (memo[key] !== undefined) {
        return memo[key];
    }

    let ans = 0;

    // Iterate through previous elements to find 
    // matching differences
    for (let j = index - 1; j >= 0; j--) {

        // If the difference matches, extend the AP
        if (arr[index] - arr[j] === diff) {
            ans = Math.max(ans, 
                           1 + solve(j, diff, arr, memo));
        }
    }

    // Store the result in the memo object
    memo[key] = ans;
    return ans;
}

// Function to find the length of the longest 
// arithmetic progression (AP) in the array
function lengthOfLongestAP(arr) {

    const n = arr.length;

    // If there are less than 3 elements, 
    // return the size
    if (n <= 2) {
        return n;
    }

    let ans = 0;

    // Memoization object to store results for solve
    const memo = {};

    // Iterate through all pairs of elements as 
    // possible first two terms
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {

            // Calculate difference and find AP 
            // using memoized recursion
            const diff = arr[j] - arr[i];
            ans = Math.max(ans, 
                           2 + solve(i, diff, arr, memo));
        }
    }

    return ans;
}

const arr = [1, 7, 10, 15, 27, 29];
console.log(lengthOfLongestAP(arr));

Output
3

Using Bottom-Up DP (Tabulation) - O(n^2) Time and O(n^2) Space

The tabulation approach iteratively builds the solution in a bottom-up manner, avoiding the use of recursion. Instead of solving smaller subproblems recursively, we use a table to store and update solutions for progressively larger subproblems.

We will create a 2D table of size n x diffRange, where dp[i][diff] represents the length of the arithmetic progression (AP) ending at index i with a common difference of diff.

The dynamic programming relation is as follows:

  • For each pair of indices (j, i) where j < i: Calculate the common difference: diff = arr[i] - arr[j]
  • If there is an AP ending at index j with the same diff: dp[i][diff] = dp[j][diff] + 1
  • Otherwise, start a new AP of length 2: dp[i][diff] = 2
C++
// C++ program to find the length of the longest 
// arithmetic progression (AP) using tabulation
#include <bits/stdc++.h>
using namespace std;

// Function to find the length of the longest 
// arithmetic progression (AP) in the array
int lengthOfLongestAP(vector<int> &arr) {
    int n = arr.size();

    // If there are less than 3 elements, 
    // return the size
    if (n <= 2) 
        return n;

    int ans = 2;

    // Create a 2D dp table where dp[i][j] stores the
    // length of the AP ending at indices i and j
    vector<unordered_map<int, int>> dp(n);

    // Iterate through all pairs of elements as 
    // possible first two terms
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < i; j++) {

            // Calculate the common difference
            int diff = arr[i] - arr[j];

            // If there's an AP ending at j with this diff,
            // extend it; otherwise, start a new AP of length 2
            dp[i][diff] = dp[j].count(diff) ? dp[j][diff] + 1 : 2;

            // Update the overall maximum length
            ans = max(ans, dp[i][diff]);
        }
    }

    return ans;
}

int main() {
    vector<int> arr = {1, 7, 10, 15, 27, 29};

    cout << lengthOfLongestAP(arr) << endl;

    return 0;
}
Java
// Java program to find the length of the longest 
// arithmetic progression (AP) using tabulation
import java.util.ArrayList;
import java.util.HashMap;

class GfG {

    // Function to find the length of the longest 
    // arithmetic progression (AP) in the array
    static int lengthOfLongestAP(ArrayList<Integer> arr) {
        
        int n = arr.size();

        // If there are less than 3 elements, 
        // return the size
        if (n <= 2) {
            return n;
        }

        int ans = 0;

        // Create a 2D HashMap to store the lengths of 
        // APs ending at each index with a given difference
        HashMap<Integer, Integer>[] dp = new HashMap[n];

        for (int i = 0; i < n; i++) {
            dp[i] = new HashMap<>();
        }

        // Iterate through all pairs of elements as 
        // possible first two terms
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < i; j++) {

                // Calculate the common difference
                int diff = arr.get(i) - arr.get(j);

                // Check if this difference was seen before
                int length = dp[j].getOrDefault(diff, 1);

                // Update the length of the AP ending at index `i`
                dp[i].put(diff, length + 1);

                // Update the global maximum length
                ans = Math.max(ans, dp[i].get(diff));
            }
        }

        return ans;
    }

    public static void main(String[] args) {

        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(7);
        arr.add(10);
        arr.add(15);
        arr.add(27);
        arr.add(29);

        System.out.println(lengthOfLongestAP(arr));
    }
}
Python
# Python program to find the length of the longest 
# arithmetic progression (AP) using tabulation

# Function to find the length of the longest
# AP in the array
def lengthOfLongestAP(arr):
    
    n = len(arr)

    # If there are less than 3 elements,
    # return the size
    if n <= 2:
        return n
    
    # Create a list of dictionaries to store
    # lengths of APs
    dp = [{} for _ in range(n)]

    ans = 0

    # Iterate through all pairs of elements as
    # possible first two terms
    for i in range(1, n):
        for j in range(i):
            
            # Calculate the common difference
            diff = arr[i] - arr[j]

            # Get the previous length or start with 1
            length = dp[j].get(diff, 1)

            # Update the length of the AP ending at index `i`
            dp[i][diff] = length + 1

            # Update the global maximum length
            ans = max(ans, dp[i][diff])
    
    return ans

if __name__ == "__main__":
    
    arr = [1, 7, 10, 15, 27, 29]

    print(lengthOfLongestAP(arr))
C#
// C# program to find the length of the longest 
// arithmetic progression (AP) using tabulation
using System;
using System.Collections.Generic;

class GfG {
  
    // Function to find the length of the longest 
    // arithmetic progression (AP) in the array
    static int LengthOfLongestAP(List<int> arr) {

        int n = arr.Count;

        // If there are less than 3 elements,
      	// return the size
        if (n <= 2) {
            return n;
        }

        // Create a list of dictionaries to store 
      	// lengths of APs
        var dp = new List<Dictionary<int, int>>();
        for (int i = 0; i < n; i++) {
            dp.Add(new Dictionary<int, int>());
        }

        int ans = 0;

        // Iterate through all pairs of elements as
        // possible first two terms
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < i; j++) {

                // Calculate the common difference
                int diff = arr[i] - arr[j];

                // Get the previous length or start with 1
                int length = dp[j].ContainsKey(diff) 
                             ? dp[j][diff] : 1;

                // Update the length of the AP ending 
              	// at index `i`
                if (!dp[i].ContainsKey(diff)) {
                    dp[i][diff] = length + 1;
                } else {
                    dp[i][diff] = Math.Max(dp[i][diff], 
                                           length + 1);
                }

                // Update the global maximum length
                ans = Math.Max(ans, dp[i][diff]);
            }
        }

        return ans;
    }

    static void Main(string[] args) {

        List<int> arr = new List<int> { 1, 7, 10, 
                                        15, 27, 29 };

        Console.WriteLine(LengthOfLongestAP(arr));
    }
}
JavaScript
// Javascript program to find the length of the longest 
// arithmetic progression (AP) using tabulation

function lengthOfLongestAP(arr) {
    const n = arr.length;

    // If there are less than 3 elements, 
    // return the size
    if (n <= 2) {
        return n;
    }

    // Create an array of maps to store lengths of APs
    const dp = Array.from({ length: n }, () => new Map());

    let ans = 0;

    // Iterate through all pairs of elements as
    // possible first two terms
    for (let i = 1; i < n; i++) {
        for (let j = 0; j < i; j++) {

            // Calculate the common difference
            const diff = arr[i] - arr[j];

            // Get the previous length or start with 1
            const length = dp[j].get(diff) || 1;

            // Update the length of the AP ending at index `i`
            dp[i].set(diff, Math.max(dp[i].get(diff) || 0, length + 1));

            // Update the global maximum length
            ans = Math.max(ans, dp[i].get(diff));
        }
    }

    return ans;
}

const arr = [1, 7, 10, 15, 27, 29];
console.log(lengthOfLongestAP(arr));

Output
3

Next Article

Similar Reads