Skip to content

Commit 496fa6a

Browse files
committedFeb 26, 2025
Add solution #413
1 parent 5e89bbb commit 496fa6a

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,7 @@
329329
409|[Longest Palindrome](./0409-longest-palindrome.js)|Easy|
330330
410|[Split Array Largest Sum](./0410-split-array-largest-sum.js)|Hard|
331331
412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy|
332+
413|[Arithmetic Slices](./0413-arithmetic-slices.js)|Medium|
332333
414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy|
333334
415|[Add Strings](./0415-add-strings.js)|Easy|
334335
416|[Partition Equal Subset Sum](./0416-partition-equal-subset-sum.js)|Medium|

‎solutions/0413-arithmetic-slices.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* 413. Arithmetic Slices
3+
* https://leetcode.com/problems/arithmetic-slices/
4+
* Difficulty: Medium
5+
*
6+
* An integer array is called arithmetic if it consists of at least three elements and if
7+
* the difference between any two consecutive elements is the same.
8+
*
9+
* For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.
10+
*
11+
* Given an integer array nums, return the number of arithmetic subarrays of nums.
12+
*
13+
* A subarray is a contiguous subsequence of the array.
14+
*/
15+
16+
/**
17+
* @param {number[]} nums
18+
* @return {number}
19+
*/
20+
var numberOfArithmeticSlices = function(nums) {
21+
if (nums.length < 3) return 0;
22+
let result = 0;
23+
24+
for (let i = 2, value = 0; i < nums.length; i++) {
25+
if (nums[i] - nums[i - 1] === nums[i - 1] - nums[i - 2]) {
26+
value++;
27+
result += value;
28+
} else {
29+
value = 0;
30+
}
31+
}
32+
33+
return result;
34+
};

0 commit comments

Comments
 (0)
Please sign in to comment.