Skip to content

Commit ffd22b8

Browse files
committedFeb 27, 2025
Add solution #446
1 parent 4af61ad commit ffd22b8

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,7 @@
354354
442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium|
355355
443|[String Compression](./0443-string-compression.js)|Medium|
356356
445|[Add Two Numbers II](./0445-add-two-numbers-ii.js)|Medium|
357+
446|[Arithmetic Slices II - Subsequence](./0446-arithmetic-slices-ii-subsequence.js)|Hard|
357358
448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy|
358359
450|[Delete Node in a BST](./0450-delete-node-in-a-bst.js)|Medium|
359360
451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium|
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 446. Arithmetic Slices II - Subsequence
3+
* https://leetcode.com/problems/arithmetic-slices-ii-subsequence/
4+
* Difficulty: Hard
5+
*
6+
* Given an integer array nums, return the number of all the arithmetic subsequences of nums.
7+
*
8+
* A sequence of numbers is called arithmetic if it consists of at least three elements and if
9+
* the difference between any two consecutive elements is the same.
10+
*
11+
* - For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences.
12+
* - For example, [1, 1, 2, 5, 7] is not an arithmetic sequence.
13+
*
14+
* A subsequence of an array is a sequence that can be formed by removing some elements (possibly
15+
* none) of the array.
16+
*
17+
* - For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].
18+
*
19+
* The test cases are generated so that the answer fits in 32-bit integer.
20+
*/
21+
22+
/**
23+
* @param {number[]} nums
24+
* @return {number}
25+
*/
26+
var numberOfArithmeticSlices = function(nums) {
27+
const dp = new Array(nums.length).fill().map(() => new Map());
28+
let result = 0;
29+
30+
for (let i = 1; i < nums.length; i++) {
31+
for (let j = 0; j < i; j++) {
32+
const diff = nums[i] - nums[j];
33+
const prev = dp[j].get(diff) || 0;
34+
const current = (dp[i].get(diff) || 0) + prev + 1;
35+
dp[i].set(diff, current);
36+
result += prev;
37+
}
38+
}
39+
40+
return result;
41+
};

0 commit comments

Comments
 (0)
Please sign in to comment.