Skip to content

Instantly share code, notes, and snippets.

@jsbonso
Created October 27, 2017 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsbonso/8dca10ad87b815001ba65d5ca6642ad3 to your computer and use it in GitHub Desktop.
Save jsbonso/8dca10ad87b815001ba65d5ca6642ad3 to your computer and use it in GitHub Desktop.
Arithmetic Slice
/*
* Returns the number of arithmetic slices in
* the given number array.
*
* Examples:
* [-1, 1, 3, 3, 3, 2, 1, 0] = 5
*
* A sequence is an Arithmetic if:
* 1. It consists of 3 elements
* 2. The difference between any two consecutive
* elements is the same
*/
function solution(A) {
var result = 0;
var dp = 0;
// Iterate through the elements
for (var i=2;i< A.length; i++){
// Check the sequence of numbers if they pass as Arithmetic
if ((A[i-1]-A[i-2]) == (A[i]-A[i-1])){
dp=1 + dp;
result += dp;
} else{
dp = 0;
}
}
// Returns -1 if result exceeds to 1 Billion
return (result > 1000000000) ? -1 : result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment