Longest Arithmetic Sequence in C++

C++Server Side ProgrammingProgramming

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

 Live Demo

#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
raja
Published on 13-Apr-2020 11:30:12
Advertisements