-
Notifications
You must be signed in to change notification settings - Fork 0
/
1027. Longest Arithmetic Subsequence
103 lines (54 loc) · 1.53 KB
/
1027. Longest Arithmetic Subsequence
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
class Solution {
public int longestArithSeqLength(int[] nums)
{
int len = 2;
int max = nums[0], min = nums[0];
for(int num : nums)
{
if(num > max)
{
max = num;
}
if(num < min)
{
min = num;
}
}
int difference = max-min;
int[] upDP = new int[max+1];
int[] downDP = new int[max+1];
for(int i = 0; i*len <= difference; i++)
{
Arrays.fill(upDP, 0);
Arrays.fill(downDP, 0);
for(int num : nums)
{
if (len < (upDP[num] = (num + i <= max) ? (upDP[num + i] + 1) : 1))
{
len = upDP[num];
}
if (len < (downDP[num] = (num - i >= 0) ? (downDP[num - i] + 1) : 1))
{
len = downDP[num];
}
}
}
return len;
/*
int n = nums.length;
int max=0;
HashMap<Integer, Integer>[] dp = new HashMap[n];
for(int i=0; i<n; i++)
{
dp[i] = new HashMap<>();
for(int j=0; j<i; j++)
{
int difference = nums[i] - nums[j];
dp[i].put(difference, dp[j].getOrDefault(difference, 1) + 1);
max = Math.max(max, dp[i].get(difference));
}
}
return max;
*/
}
}