Simply check the difference between adjacent elements.
If it's different from the previous one, do:
(1) update the counts
(2) update the
prediff and the
head (the starting index of this
def numberOfArithmeticSlices(self, A): if len(A) <= 2: return 0 i, count, head, prediff = 2, 0, 0, A-A while i < len(A): diff = A[i] - A[i-1] if diff != prediff: count += (i-head-2)*(i-head-1)/2 #from head to i-1 head, prediff = i-1, diff i += 1 return count + (i-head-2)*(i-head-1)/2