Longest Arithmetic Subsequence LeetCode solution in JavaScript

1
var longestArithSeqLength = function (nums) {
2
if (nums === null || nums.length === 0) {
3
return 0;
4
}
5
let diffMap = new Array(nums.length).fill(0).map(() => new Map());
6
let maxLen = 1;
7
for (let i = 0; i < nums.length; i++) {
8
for (let j = 0; j < i; j++) {
9
let diff = nums[i] - nums[j];
10
// if prev element has an ongoing arithmetic sequence with the same common difference
11
// we simply add 1 to the length of that ongoing sequence, hence diffMap[j].get(diff) + 1
12
// else, we start a new arithmetic sequence, initial length is 2
13
diffMap[i].set(diff, diffMap[j].get(diff) + 1 || 2);
14
maxLen = Math.max(maxLen, diffMap[i].get(diff));
15
}
16
}
17
return maxLen;
18
// T.C: O(N^2)
19
// S.C: O(N^2)
20
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0