Arithmetic Slices

medium array dp

Problem

Count the number of contiguous subarrays of length ≥ 3 whose consecutive differences are all equal (arithmetic progressions).

Inputnums = [1, 2, 3, 4]
Output3
Slices: [1,2,3], [2,3,4], [1,2,3,4].

def number_of_arithmetic_slices(nums):
    total, run = 0, 0
    for i in range(2, len(nums)):
        if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]:
            run += 1
            total += run
        else:
            run = 0
    return total
function numberOfArithmeticSlices(nums) {
  let total = 0, run = 0;
  for (let i = 2; i < nums.length; i++) {
    if (nums[i] - nums[i - 1] === nums[i - 1] - nums[i - 2]) {
      run++;
      total += run;
    } else {
      run = 0;
    }
  }
  return total;
}
class Solution {
    public int numberOfArithmeticSlices(int[] nums) {
        int total = 0, run = 0;
        for (int i = 2; i < nums.length; i++) {
            if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) {
                run++;
                total += run;
            } else run = 0;
        }
        return total;
    }
}
int numberOfArithmeticSlices(vector<int>& nums) {
    int total = 0, run = 0;
    for (int i = 2; i < (int)nums.size(); i++) {
        if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) {
            run++;
            total += run;
        } else run = 0;
    }
    return total;
}
Time: O(n) Space: O(1)