
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Longest Consecutive Sequence in Python
- Longest Arithmetic Subsequence of Given Difference in C++
- Binary Tree Longest Consecutive Sequence in C++
- Finding the longest "uncommon" sequence in JavaScript
- 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
- Program to find length of longest consecutive 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
- 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
- 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