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).
1import java.util.*;
2
3public class ArithmeticSlices {
4 public int numberOfArithmeticSlices(int[] nums) {
5 int n = nums.length;
6 int total = 0;
7 Map<Long, Integer>[] dp = new Map[n];
8
9 for (int i = 0; i < n; i++) {
10 dp[i] = new HashMap<>();
11 for (int j = 0; j < i; j++) {
12 long diff = (long) nums[i] - (long) nums[j];
13 int count_j = dp[j].getOrDefault(diff, 0);
14 dp[i].put(diff, dp[i].getOrDefault(diff, 0) + count_j + 1);
15 total += count_j;
16 }
17 }
18 return total;
19 }
20
21 public static void main(String[] args) {
22 ArithmeticSlices as = new ArithmeticSlices();
23 int[] nums = {2, 4, 6, 8, 10};
24 System.out.println(as.numberOfArithmeticSlices(nums));
25 }
26}
In this Java solution, an array of `Map
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 JavaScript function recursively forms all possible combinations of subsequences. Each subsequence is checked for arithmetic properties, and results are stored incrementally. It's intended more for understanding rather than performance given its complexity.