- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Longest Arithmetic Sequence in C++

Suppose we have an array A of integers, we have to return the length of the longest arithmetic subsequence in A. As you know that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic when B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1). So if the input is like [9,4,7,2,10], then the output will be 3. As the longest subsequence is [4,7,10].

To solve this, we will follow these steps −

Make a map dp, n := size of A, set ret := 2

for i in range 0 to n – 1

for j in range 0 to i – 1

diff := A[j] – A[i]

dp[i, diff] := 1 + dp[j, diff]

ret := max of 1 + dp[i, diff] and ret

return ret

Let us see the following implementation to get better understanding −

## Example

#include <bits/stdc++.h> using namespace std; class Solution { public: int longestArithSeqLength(vector<int>& A) { unordered_map <int, unordered_map <int, int> > dp; int n = A.size(); int ret = 2; for(int i = 0; i < n; i++){ for(int j = 0; j < i; j++){ int diff = A[j] - A[i]; dp[i][diff] = 1 + dp[j][diff]; ret = max(1 + dp[i][diff], ret); } } return ret; } }; main(){ vector<int> v1 = {9,4,7,2,10}; Solution ob; cout << (ob.longestArithSeqLength(v1)); }

### Input

[9,4,7,2,10]

## Output

3

- Related Questions & Answers
- Longest Consecutive Sequence in Python
- Longest Arithmetic Subsequence of Given Difference in C++
- Binary Tree Longest Consecutive Sequence in C++
- Binary Tree Longest Consecutive Sequence II in C++
- Program to find removed term from arithmetic sequence in Python
- Finding the missing number in an arithmetic progression sequence in JavaScript
- Finding the longest "uncommon" sequence in JavaScript
- Program to find length of longest consecutive sequence in Python
- Finding the longest non-negative sum sequence using JavaScript
- Program to check we can make arithmetic progression from sequence in Python
- Program to check how many queries finds valid arithmetic sequence in Python
- How to find longest repetitive sequence in a string in Python?
- Longest path in 2-D that contains increasing sequence in JavaScript
- Length of the longest possible consecutive sequence of numbers in JavaScript
- Program to find length of longest arithmetic subsequence with constant difference in Python

Advertisements