clueless coding // TODO: be smarter

LeetCode 413. Arithmetic Slices: Java Solution



Problem Statement


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

For reference, here are some example arithmetic sequences:

0, 5, 10, 15 - difference: 5
5, 5, 5, 5 - difference: 0

The following sequence is not arithmetic.

2, 3, 6, 15

Given an array of integers A, create a function that returns the total number of arithmetic slices that you can create from it.

Function Signature (Java):
  int numberOfArithmeticSlices(int[] A)

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

Outputs:
  3

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



TL;DR Code Solution


public int numberOfArithmeticSlices(int[] A) {

    int result = 0;
    int curr = 0;

    for (int i = 2; i < A.length; i++) {

        if (A[i] - A[i-1] == A[i-1] - A[i-2]) {
            curr += 1;
        }
        else {
            curr = 0;
        }
        result += curr;
    }

    return result;

}