- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Arithmetic Slices in C++
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]
- if a[i] – a[i – 1] = a[i – 1] – a[i – 2], then
- return ret
Example (C++)
Let us see the following implementation to get better understanding −
#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