-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path1027.java
More file actions
62 lines (56 loc) · 2.22 KB
/
1027.java
File metadata and controls
62 lines (56 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
__________________________________________________________________________________________________
sample 10 ms submission
class Solution {
public int longestArithSeqLength(int[] A) {
int N = A.length;
int[][] dp = new int[N][N];
int[] positions = new int[20000];
Arrays.fill(positions, -1);
int max = 0;
for(int i = 0; i < N; i++){
for(int j = i + 1; j < N; j++){
int prev = A[i] - (A[j] - A[i]);
if(prev < 0 || positions[prev] == -1) continue;
dp[i][j] = dp[positions[prev]][i] + 1;
max = Math.max(max, dp[i][j]);
}
positions[A[i]] = i;
}
return max + 2;
}
}
__________________________________________________________________________________________________
sample 35440 kb submission
class Solution {
public int longestArithSeqLength(int[] input) {
Map<Integer, List<Integer>> map = new HashMap<>();
for (int i = 0; i < input.length; i++) {
List<Integer> subList = map.computeIfAbsent(input[i], z -> new ArrayList<>());
subList.add(i);
}
int longest = 2;
for (int i = 0; i < input.length - 1; i++) {
for (int j = i + 1; j < input.length - 1; j++) {
int diff = input[i] - input[j];
longest = Math.max(longest, longestArithSeqLength(input, map, j, diff) + 2);
}
}
return longest;
}
public int longestArithSeqLength(int[] input, Map<Integer, List<Integer>> map, int orig_idx, int diff) {
int longest = 0;
int expected = input[orig_idx] - diff;
List<Integer> idxList = map.get(expected);
// System.out.printf("Idx: %d, diff: %d, expected: %d, idxList: %s\n", orig_idx, diff, expected, idxList);
if (idxList != null) {
for (Integer idx : idxList) {
if (idx <= orig_idx) {
continue;
}
longest = Math.max(longest, longestArithSeqLength(input, map, idx, diff) + 1);
}
}
return longest;
}
}
__________________________________________________________________________________________________