Arithmetic Slices II - Subsequence LeetCode solution in Java

1
class Solution {
2
public int numberOfArithmeticSlices(int[] nums) {
3
int n = nums.length;
4

5
HashMap<Integer, Integer>[] dp = new HashMap[n];
6

7
for (int i = 0; i < n; i++) {
8
dp[i] = new HashMap<Integer, Integer>();
9
}
10

11
int ans = 0;
12

13
for (int i = 1; i < n; i++) {
14
for (int j = 0; j < i; j++) {
15
long cd = (long) nums[i] - (long) nums[j];
16

17
if (cd <= Integer.MIN_VALUE || cd >= Integer.MAX_VALUE) {
18
continue;
19
}
20

21
int endingAtj = dp[j].getOrDefault((int) cd, 0);
22
int endingAti = dp[i].getOrDefault((int) cd, 0);
23

24
ans += endingAtj;
25

26
dp[i].put((int) cd, endingAtj + endingAti + 1);
27
}
28
}
29

30
return ans;
31
}
32
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0