LeetCode: Arithmetic Slices Solution

1/**
2 * @param {number[]} A
3 * @return {number}
4 */
5var numberOfArithmeticSlices = function (A) {
6 const N = A.length
7 let res = 0
8 let acc = 0
9 for (let i = 2; i < N; i++) {
10 if (A[i] - A[i - 1] === A[i - 1] - A[i - 2]) {
11 acc++
12 res += acc
13 } else {
14 acc = 0
15 }
16 }
17 return res
18}
19
20var numberOfArithmeticSlices = function (A) {
21 const N = A.length
22 let res = 0
23 let acc = 0
24 for (let i = 2; i < N; i++) {
25 if (A[i] - A[i - 1] === A[i - 1] - A[i - 2]) {
26 acc++
27 } else {
28 res += (acc * (acc + 1)) / 2
29 acc = 0
30 }
31 }
32 res += (acc * (acc + 1)) / 2
33 return res
34}

Comments

Loading comments...

Tags

leetcode

math

dynamic programming

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Minimum Remove To Make Valid Parentheses

Feb 19, 2021

Previous Post

HoningJS

Search Posts