Arithmetic Slices II - Subsequence in C++


Suppose we have an array A, where N numbers are present. A subsequence slice of that array is any sequence of integers like (K0, K1, K2, … Kn) such that 0 <= K0 < K1 < K2 < … < Kn < N. A subsequence slice (K0, K1, K2, … Kn) of A is called arithmetic slice, if the sequence A[K0], A[K1], … A[Kn] is arithmetic, so this means that n >= 2. So we have to return the number of arithmetic slices.

So if the input is like [2,4,6,8,10], then the answer will be 7, as there are 7 arithmetic slices. [2,4,6], [2,4,10], [4,6,8], [6,8,10], [2,4,6,8], [4,6,8,10], [2,4,6,8,10],

To solve this, we will follow these steps −

  • ret := 0
  • Define one map dp another map cnt
  • Define one set s by taking elements from A
  • n := size of A
  • for initialize i := 1, when i < n, update (increase i by 1), do −
    • for initialize j := i - 1, when j >= 0, update (decrease j by 1), do −
      • diff := A[i] - A[j]
      • if diff <= -inf or diff > inf, then −
        • Ignore following part, skip to the next iteration
      • temp := dp[j, diff] when diff is in the map dp[j], otherwise 0
      • ret := ret + temp
      • if (A[i] + diff) is present in s, then −
        • dp[i, diff] := dp[i, diff] + temp + 1
  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
   int numberOfArithmeticSlices(vector<int>& A) {
      int ret = 0;
      unordered_map <lli, unordered_map <lli, lli> > dp, cnt;
      unordered_set <int> s (A.begin(), A.end());
      int n = A.size();
      for(int i = 1; i < n; i++){
         for(int j = i - 1; j >= 0; j--){
            lli diff = (lli)A[i] - (lli)A[j];
            if(diff <= INT_MIN || diff > INT_MAX) continue;
            int temp = dp[j].count(diff) ? dp[j][diff] : 0;
            ret += temp;
            if(s.count(A[i] + diff))dp[i][diff] += temp + 1;
         }
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<int> v = {2,4,6,8,10};
   cout << (ob.numberOfArithmeticSlices(v));
}

Input

{2,4,6,8,10}

Output

7

Updated on: 01-Jun-2020

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements