clueless coding // TODO: be smarter

LeetCode 413. Arithmetic Slices: C++ Solution



Problem Statement


Arithmetic sequences consist of at least three elements and the difference between any two consecutive elements in the array is the same.

For reference, some arithmetic sequences:

1, 2, 3, 4, 5, 6 - difference: 1
7, 7, 7, 7 - difference: 0
1, 3, 5, 7 - difference: 2

The following sequence is not arithmetic.

1, 3, 7, 15

Given an array of integers A, write a function that returns the number of arithmetic slices in it.

Function Signature (C++):
  int numberOfArithmeticSlices(vector<int>& A)

Inputs:
  A = [1, 2, 3, 4]

Outputs:
  3

We can create three arithmetic sequences from A:
[1, 2, 3]
[2, 3, 4]
[1, 2, 3, 4]



TL;DR Code Solution


int numberOfArithmeticSlices(vector<int>& A) {

    int cur = 0;
    int result = 0;

    for (int i = 2; i < A.size(); i++) {
        if (A[i] - A[i-1] == A[i-1] - A[i-2]) {
            cur += 1;
        }
        else {
            cur = 0;
        }
        result += cur;
    }

    return result;

}