Arithmetic Slices in C++

C++Server Side ProgrammingProgramming

Suppose we have a sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. So for example, these are arithmetic sequence: [1, 3, 5, 7, 9], [7, 7, 7, 7], [3, -1, -5, -9], But the following sequence is not arithmetic. [1, 1, 2, 5, 7]

Now a zero-indexed array A consisting of N numbers is given. A slice of that given array is any pair of integers (P, Q) such that 0 <= P < Q < N. Here a slice (P, Q) of array A is called arithmetic if the sequence: A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. The function should find the number of arithmetic slices in the array A.

So if the input is like [1,2,3,4], then the output will be 3, as the elements are [1,2,3], [2,3,4] and [1,2,3,4]

To solve this, we will follow these steps −

  • ret := 0, n := size of A, create an array dp of size n
  • for i in range 2 to n – 1
    • if a[i] – a[i – 1] = a[i – 1] – a[i – 2], then
      • dp[i] := 1 + dp[i - 1]
      • increase ret by dp[i]
  • return ret

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
      int numberOfArithmeticSlices(vector<int>& A) {
         int ret = 0;
         int n = A.size();
         vector <int> dp(n);
         for(int i = 2; i < n; i++){
            if(A[i] - A[i - 1] == A[i - 1] - A[i - 2]){
               dp[i] = 1 + dp[i - 1];
               ret += dp[i];
            }
         }
         return ret;
      }  
};
main(){
   vector<int> v = {1,2,3,4};
   Solution ob;
   cout << (ob.numberOfArithmeticSlices(v));
}

Input

[1,2,3,4]

Output

3
raja
Published on 30-Apr-2020 08:07:41
Advertisements