g0401_0500.s0446_arithmetic_slices_ii_subsequence.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0401_0500.s0446_arithmetic_slices_ii_subsequence;
// #Hard #Array #Dynamic_Programming #2022_07_16_Time_68_ms_(99.15%)_Space_76.2_MB_(89.36%)
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Solution {
public int numberOfArithmeticSlices(int[] arr) {
Map> indexes = new HashMap<>();
int[][] length = new int[arr.length][arr.length];
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
List ix = indexes.get(arr[i] - (arr[j] - (long) arr[i]));
if (ix == null) {
continue;
}
for (int k : ix) {
length[i][j] += length[k][i] + 1;
}
count += length[i][j];
}
indexes.computeIfAbsent((long) arr[i], k -> new ArrayList<>()).add(i);
}
return count;
}
}