Arithmetic Slices - Faster than 100% C++ solutions and also very easy to understand
Problem Statement:
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
- For example,
[1,3,5,7,9],[7,7,7,7], and[3,-1,-5,-9]are arithmetic sequences.
Given an integer array nums, return the number of arithmetic subarrays of nums.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: nums = [1,2,3,4] Output: 3 Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.
Example 2:
Input: nums = [1] Output: 0
Constraints:
1 <= nums.length <= 5000-1000 <= nums[i] <= 1000
Solution:
Given you have a arithmetic sequence (AS) of length 4 as in the example, you can quickly see that:
- Number of AS of length 3 = (4-3+1)=2
- Number of AS of length 4 = (4-4+1)=1
Hence, Number of AS = 2+1 = 3
You can extend this logic to this:
Given an AS of maximum length L, total number of AS=1+2+3+..+L-2 = 1/2*(L-2)*(L-1)
So, what we need to do is as we traverse through the array, find out the AS (we keep moving the 2nd pointer till the AS is finished) and then calculate the total number of AS using above formula.
Now for the fun part:
class Solution {
public:
int numberOfArithmeticSlices(vector<int>& nums) {
int n=nums.size(), i=0, res=0;
while (i<n-2)
{
int start=i;
while (i<n-2 && nums[i+1]-nums[i]==nums[i+2]-nums[i+1]) i++;
int L = i+2-start;
int num_subs = (L-2)*(L-1)/2;
res += num_subs;
i++;
}
return res;
}
};