Sponsored
Sponsored
This approach uses dynamic programming and hashmaps to calculate arithmetic subsequences efficiently. For each index, we maintain a hashmap that tracks the count of different differences (arithmetic differences) and the number of subsequences that end with that difference at the given index. This allows us to build potential subsequences as we iterate over the array.
Time Complexity: O(n^2), where n is the length of the input array.
Space Complexity: O(n * m), where m is the number of possible differences (limited by the constraint of 31-bit integer).
1function numberOfArithmeticSlices(nums) {
2 const n = nums.length;
3 let total = 0;
4 const dp = Array(n).fill(0).map(() => new Map());
5
6 for (let i = 0; i < n; i++) {
7 for (let j = 0; j < i; j++) {
8 const diff = nums[i] - nums[j];
9 const countAtJ = dp[j].get(diff) || 0;
10 dp[i].set(diff, (dp[i].get(diff) || 0) + countAtJ + 1);
11 total += countAtJ;
12 }
13 }
14 return total;
15}
16
17// Test
18console.log(numberOfArithmeticSlices([2, 4, 6, 8, 10]));
In this JavaScript implementation, a map is created for each element in the nums array. The map keeps track of the count of subsequences for each possible difference. This system uses pairs of indices to calculate and propagate counts recursively.
This approach considers all possible subsequences (using combinations) and checks if each subsequence is arithmetic. Although not efficient, it can be used to demonstrate the logic on small arrays to understand the problem better.
Time Complexity: O(n * 2^n) for combinations, where n is length of `nums`.
Space Complexity: O(n) given additional space for combinations.
1
This Python solution directly generates combinations, checks their arithmetic property, and accumulates the count. The approach demonstrates brute-force searching across combination space, understandable but inefficiently scales poorly.