Created
October 27, 2017 08:46
-
-
Save jsbonso/8dca10ad87b815001ba65d5ca6642ad3 to your computer and use it in GitHub Desktop.
Arithmetic Slice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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