VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-arithmetic-progression-with-the-given-common-difference/

⇱ Longest arithmetic progression that can be formed with the given common difference d - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest arithmetic progression that can be formed with the given common difference d

Last Updated : 26 Aug, 2022

Given an unsorted array a[] of size n and an integer d which is the common difference, the task is to find the length of the longest AP that can be formed for all j, greater than some i(<n), 

if a[j] = a[i] + (j-i) * d

i.e. a[j] is in the AP of a[i] from index i to j.

Examples: 

Input: n = 6, d = 2 
arr[] = {1, 2, 5, 7, 9, 85} 
Output:
The longest AP, taking indices into consideration, is [1, 5, 7, 9] 
since 5 is 2 indices ahead of 1 and would fit in the AP if started 
from index 0. as 5 = 1 + (2 - 0) * 2. So the output is 4.

Input: n = 10, d = 3 
arr[] = {1, 4, 2, 5, 20, 11, 56, 100, 20, 23} 
Output:
The longest AP, taking indices into consideration, is [2, 5, 11, 20, 23] 
since 11 is 2 indices ahead of 5 and 20 is 3 indices ahead of 11. So they 
would fit in the AP if started from index 2. 

Naive Approach: For each element calculate the length of the longest AP it could form and print the maximum among them. It involves O(n2) time complexity.

An efficient approach is to use Hashing.
Create a map where the key is the starting element of an AP and its value is the number of elements in that AP. The idea is to update the value at key 'a'(which is at index i and whose starting element is not yet there in the map) by 1 whenever the element at index j(>i) could be in the AP of 'a'(as the starting element). Then we print the maximum value among all values in the map.

Implementation:


Output
5

Complexity Analysis:

  • Time Complexity: O(n)
  • Auxiliary Space: O(n)
Comment
Article Tags: