The Wayback Machine - https://web.archive.org/web/20240804233402/https://www.geeksforgeeks.org/count-arithmetic-progression-subsequences-array/
Open In App

Count of AP (Arithmetic Progression) Subsequences in an array

Last Updated : 12 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Given an array of n positive integers. The task is to count the number of Arithmetic Progression subsequence in the array. Note: Empty sequence or single element sequence is Arithmetic Progression. 1 <= arr[i] <= 1000000.
Examples: 
 

Input : arr[] = { 1, 2, 3 }
Output : 8
Arithmetic Progression subsequence from the 
given array are: {}, { 1 }, { 2 }, { 3 }, { 1, 2 },
{ 2, 3 }, { 1, 3 }, { 1, 2, 3 }.

Input : arr[] = { 10, 20, 30, 45 }
Output : 12

Input : arr[] = { 1, 2, 3, 4, 5 }
Output : 23

 

Recommended Practice

Since empty sequence and single element sequence is also arithmetic progression, so we initialize the answer with n(number of element in the array) + 1. 
Now, we need to find the arithmetic progression subsequence of length greater than or equal to 2. Let minimum and maximum of the array be minarr and maxarr respectively. Observe, in all the arithmetic progression subsequences, the range of common difference will be from (minarr – maxarr) to (maxarr – minarr). Now, for each common difference, say d, calculate the subsequence of length greater than or equal to 2 using dynamic programming. 
Let dp[i] be the number of subsequence that end with arr[i] and have common difference of d. So, 
 

The number of subsequence of length greater than or equal to 2 with common difference d is sum of dp[i] – 1, 0 <= i = 2 with difference d. To speed up, store the sum of dp[j] with arr[j] + d = arr[i] and j < i.
Below is implementation of above idea :
 

C++




// C++ program to find number of AP
// subsequences in the given array
#include<bits/stdc++.h>
#define MAX 1000001
using namespace std;
  
int numofAP(int a[], int n)
{
    // initializing the minimum value and
    // maximum value of the array.
    int minarr = INT_MAX, maxarr = INT_MIN;
  
    // Finding the minimum and maximum
    // value of the array.
    for (int i = 0; i < n; i++)
    {
        minarr = min(minarr, a[i]);
        maxarr = max(maxarr, a[i]);
    }
  
    // dp[i] is going to store count of APs ending
    // with arr[i].
    // sum[j] is going to store sum of all dp[]'s
    // with j as an AP element.
    int dp[n], sum[MAX];
  
    // Initialize answer with n + 1 as single elements
    // and empty array are also DP.
    int ans = n + 1;
  
    // Traversing with all common difference.
    for (int d=(minarr-maxarr); d<=(maxarr-minarr); d++)
    {
        memset(sum, 0, sizeof sum);
  
        // Traversing all the element of the array.
        for (int i = 0; i < n; i++)
        {
            // Initialize dp[i] = 1.
            dp[i] = 1;
  
            // Adding counts of APs with given differences
            // and a[i] is last element.  
            // We consider all APs where an array element
            // is previous element of AP with a particular 
            // difference
            if (a[i] - d >= 1 && a[i] - d <= 1000000)
                dp[i] += sum[a[i] - d];
  
            ans += dp[i] - 1;
            sum[a[i]] += dp[i];
        }
    }
  
    return ans;
}
  
// Driver code
int main()
{
    int arr[] = { 1, 2, 3 };
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << numofAP(arr, n) << endl;
    return 0;
}


Java




// Java program to find number of AP
// subsequences in the given array
import java.util.Arrays;
  
class GFG {
      
    static final int MAX = 1000001;
  
    static int numofAP(int a[], int n)
    {
          
        // initializing the minimum value and
        // maximum value of the array.
        int minarr = +2147483647;
        int maxarr = -2147483648;
  
        // Finding the minimum and maximum
        // value of the array.
        for (int i = 0; i < n; i++) {
            minarr = Math.min(minarr, a[i]);
            maxarr = Math.max(maxarr, a[i]);
        }
  
        // dp[i] is going to store count of 
        // APs ending with arr[i].
        // sum[j] is going to store sum of 
        // all dp[]'s with j as an AP element.
        int dp[] = new int[n];
        int sum[] = new int[MAX];
  
        // Initialize answer with n + 1 as 
        // single elements and empty array 
        // are also DP.
        int ans = n + 1;
  
        // Traversing with all common 
        // difference.
        for (int d = (minarr - maxarr); 
                d <= (maxarr - minarr); d++) 
        {
            Arrays.fill(sum, 0);
  
            // Traversing all the element 
            // of the array.
            for (int i = 0; i < n; i++) {
                  
                // Initialize dp[i] = 1.
                dp[i] = 1;
  
                // Adding counts of APs with
                // given differences and a[i] 
                // is last element.
                // We consider all APs where 
                // an array element is previous 
                // element of AP with a particular
                // difference
                if (a[i] - d >= 1 && 
                             a[i] - d <= 1000000)
                    dp[i] += sum[a[i] - d];
  
                ans += dp[i] - 1;
                sum[a[i]] += dp[i];
            }
        }
  
        return ans;
    }
      
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3 };
        int n = arr.length;
          
        System.out.println(numofAP(arr, n));
    }
}
  
// This code is contributed by Anant Agarwal.


Python3




# Python program to find number of AP
# subsequences in the given array
  
MAX = 1000001
  
def numofAP(a, n):
  
    # initializing the minimum value and
    # maximum value of the array.
    minarr = +2147483647
    maxarr = -2147483648
  
    # Finding the minimum and 
    # maximum value of the array.
    for i in range(n):
        minarr = min(minarr, a[i])
        maxarr = max(maxarr, a[i])
      
  
    # dp[i] is going to store count of APs ending
    # with arr[i].
    # sum[j] is going to store sum of all dp[]'s
    # with j as an AP element.
    dp = [0 for i in range(n + 1)]
      
  
    # Initialize answer with n + 1 as single 
    # elements and empty array are also DP.
    ans = n + 1
  
    # Traversing with all common difference.
    for d in range((minarr - maxarr), (maxarr - minarr) + 1):
        sum = [0 for i in range(MAX + 1)]
          
        # Traversing all the element of the array.
        for i in range(n):
          
            # Initialize dp[i] = 1.
            dp[i] = 1
  
            # Adding counts of APs with given differences
            # and a[i] is last element. 
            # We consider all APs where an array element
            # is previous element of AP with a particular 
            # difference
            if (a[i] - d >= 1 and a[i] - d <= 1000000):
                dp[i] += sum[a[i] - d]
  
            ans += dp[i] - 1
            sum[a[i]] += dp[i]
  
    return ans
  
# Driver code
arr = [ 1, 2, 3 ]
n = len(arr)
  
print(numofAP(arr, n))
  
# This code is contributed by Anant Agarwal.


C#




// C# program to find number of AP
// subsequences in the given array
using System;
  
class GFG {
      
    static int MAX = 1000001;
  
    // Function to find number of AP
    // subsequences in the given array
    static int numofAP(int []a, int n)
    {
          
        // initializing the minimum value and
        // maximum value of the array.
        int minarr = +2147483647;
        int maxarr = -2147483648;
        int i;
          
        // Finding the minimum and maximum
        // value of the array.
        for (i = 0; i < n; i++) 
        {
            minarr = Math.Min(minarr, a[i]);
            maxarr = Math.Max(maxarr, a[i]);
        }
  
        // dp[i] is going to store count of 
        // APs ending with arr[i].
        // sum[j] is going to store sum of 
        // all dp[]'s with j as an AP element.
        int []dp = new int[n];
        int []sum = new int[MAX];
  
        // Initialize answer with n + 1 as 
        // single elements and empty array 
        // are also DP.
        int ans = n + 1;
  
        // Traversing with all common 
        // difference.
        for (int d = (minarr - maxarr); 
                 d <= (maxarr - minarr); d++) 
        {
              
            for(i = 0; i < MAX; i++)
            sum[i]= 0;
          
            // Traversing all the element 
            // of the array.
            for ( i = 0; i < n; i++)
            {
                  
                // Initialize dp[i] = 1.
                dp[i] = 1;
  
                // Adding counts of APs with
                // given differences and a[i] 
                // is last element.
                // We consider all APs where 
                // an array element is previous 
                // element of AP with a particular
                // difference
                if (a[i] - d >= 1 && 
                    a[i] - d <= 1000000)
                    dp[i] += sum[a[i] - d];
  
                ans += dp[i] - 1;
                sum[a[i]] += dp[i];
            }
        }
  
        return ans;
    }
      
    // Driver code
    public static void Main()
    {
        int []arr = {1, 2, 3};
        int n = arr.Length;
          
        Console.WriteLine(numofAP(arr, n));
    }
}
  
// This code is contributed by vt_m.


Javascript




<script>
    // Javascript program to find number of AP
    // subsequences in the given array
      
    let MAX = 1000001;
    
    function numofAP(a, n)
    {
            
        // initializing the minimum value and
        // maximum value of the array.
        let minarr = +2147483647;
        let maxarr = -2147483648;
    
        // Finding the minimum and maximum
        // value of the array.
        for (let i = 0; i < n; i++) {
            minarr = Math.min(minarr, a[i]);
            maxarr = Math.max(maxarr, a[i]);
        }
    
        // dp[i] is going to store count of 
        // APs ending with arr[i].
        // sum[j] is going to store sum of 
        // all dp[]'s with j as an AP element.
        let dp = new Array(n);
        let sum = new Array(MAX);
    
        // Initialize answer with n + 1 as 
        // single elements and empty array 
        // are also DP.
        let ans = n + 1;
    
        // Traversing with all common 
        // difference.
        for (let d = (minarr - maxarr); 
                d <= (maxarr - minarr); d++) 
        {
            sum.fill(0);
    
            // Traversing all the element 
            // of the array.
            for (let i = 0; i < n; i++) {
                    
                // Initialize dp[i] = 1.
                dp[i] = 1;
    
                // Adding counts of APs with
                // given differences and a[i] 
                // is last element.
                // We consider all APs where 
                // an array element is previous 
                // element of AP with a particular
                // difference
                if (a[i] - d >= 1 && 
                             a[i] - d <= 1000000)
                    dp[i] += sum[a[i] - d];
    
                ans += dp[i] - 1;
                sum[a[i]] += dp[i];
            }
        }
    
        return ans;
    }
      
    let arr = [ 1, 2, 3 ];
    let n = arr.length;
  
    document.write(numofAP(arr, n));
      
</script>


Output : 
 

8

Time complexity: O(n*d) given an array of n positive integers and d is the difference between the maximum and minimum value in the array.

Auxiliary Space: O(MAX)

 



Previous Article
Next Article

Similar Reads

Count common elements in two arrays which are in Arithmetic Progression
Given two arrays arr1[] and arr2[] of size M and N respectively. Both arrays are in Arithmetic Progression and the first element of both arrays is the same. The task is to find the number of common elements in arr1[] and arr2[].Examples: Input: arr1[] = {2, 3, 4, 5, 6}, arr2[] = {2, 4, 6, 8, 10} Output: 3 Explanation: Common elements are {2, 4, 6}I
15+ min read
Count of subarrays forming an Arithmetic Progression (AP)
Given an array arr[] of size N, the task is to find the count of subarrays of at least length 2, such that the difference between the consecutive elements of those subarrays remains the same throughout i.e. the elements of the subarray forms an AP. Examples: Input: arr[] = {8, 7, 4, 1, 0} Output: 5 Explanation: All subarrays of size greater than 1
15 min read
Minimum De-arrangements present in array of AP (Arithmetic Progression)
Given an array of n-elements. Given array is a permutation of some Arithmetic Progression. Find the minimum number of De-arrangements present in that array so as to make that array an Arithmetic progression. Examples: Input : arr[] = [8, 6, 10 ,4, 2] Output : Minimum De-arrangement = 3 Explanation : arr[] = [10, 8, 6, 4, 2] is permutation which for
6 min read
Queries to check if array elements from indices [L, R] forms an Arithmetic Progression or not
Given an array arr[] consisting of N integers and an array Q[][2] consisting of M queries of the form {L, R}, the task for each query is to check if array elements over the range [L, R] forms an Arithmetic Progression or not. If found to be true, print "Yes". Otherwise, print "No". Examples: Input: arr[] = {1, 3, 5, 7, 6, 5, 4, 1}, Q[][] = {{0, 3},
14 min read
Convert given array to Arithmetic Progression by adding an element
Given an array arr[], the task is to find an element that can be added to the array in order to convert it to Arithmetic Progression. If it's impossible to convert the given array into an AP, then print -1. Examples: Input: arr[] = {3, 7} Output: 11 3, 7 and 11 is a finite AP sequence. Input: a[] = {4, 6, 8, 15} Output: -1 Approach: Sort the array
8 min read
Change one element in the given array to make it an Arithmetic Progression
Given an array which is an original arithmetic progression with one element changed. The task is to make it an arithmetic progression again. If there are many such possible sequences, return any one of them. The length of the array will always be greater than 2. Examples: Input : arr = [1, 3, 4, 7] Output : arr = [1, 3, 5, 7] The common difference
7 min read
Find elements in Array whose positions forms Arithmetic Progression
Given an array A[] of N integers. Consider an integer num such that num occurs in the array A[] and all the positions of num, sorted in increasing order forms an arithmetic progression. The task is to print all such pairs of num along with the common difference of the arithmetic progressions they form. Examples : Input: N = 8, A = {1, 2, 1, 3, 1, 2
11 min read
Check whether Arithmetic Progression can be formed from the given array
Given an array of n integers. The task is to check whether an arithmetic progression can be formed using all the given elements. If possible print "Yes", else print "No". Examples: Input : arr[] = {0, 12, 4, 8} Output : Yes Rearrange given array as {0, 4, 8, 12} which forms an arithmetic progression. Input : arr[] = {12, 40, 11, 20} Output : NoReco
15+ min read
Number of GP (Geometric Progression) subsequences of size 3
Given n elements and a ratio r, find the number of G.P. subsequences with length 3. A subsequence is considered GP with length 3 with ration r. Examples: Input : arr[] = {1, 1, 2, 2, 4} r = 2 Output : 4 Explanation: Any of the two 1s can be chosen as the first element, the second element can be any of the two 2s, and the third element of the subseq
15+ min read
PHP program to print an arithmetic progression series using inbuilt functions
We have to print an arithmetic progressive series in PHP, between two given numbers a and b both including, a given common arithmetic difference of d. Examples: Input : $a = 200, $b = 250, $d = 10 Output : 200, 210, 220, 230, 240, 250 Input : $a = 10, $b = 100, $d = 20 Output : 10, 30, 50, 70, 90This problem can be solved using loops by iterating f
2 min read
three90RightbarBannerImg