Skip to content

Commit 3b115b9

Browse files
committed
Implement longest-arithmetic-subsequence
name: longest-arithmetic-subsequence url: https://leetcode.com/problems/longest-arithmetic-subsequence difficulty: 2 time: 448 ms time-rank: 20.7 % time-complexity: O(N^2) space: 141.3 MB space-rank: 66.83 % space-complexity: O(N*M) Fixes #325 Signed-off-by: Christopher Friedt <[email protected]>
1 parent 7c2501f commit 3b115b9

2 files changed

+79
-0
lines changed
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* Copyright (c) 2021, Christopher Friedt
3+
*
4+
* SPDX-License-Identifier: MIT
5+
*/
6+
7+
#include <gtest/gtest.h>
8+
9+
#include "longest-arithmetic-subsequence.cpp"
10+
11+
using namespace std;
12+
13+
TEST(LongestArithmeticSubsequence, 3_6_9_12) {
14+
vector<int> A = {3, 6, 9, 12};
15+
EXPECT_EQ(4, Solution().longestArithSeqLength(A));
16+
}
17+
18+
TEST(LongestArithmeticSubsequence, 9_4_7_2_10) {
19+
vector<int> A = {9, 4, 7, 2, 10};
20+
EXPECT_EQ(3, Solution().longestArithSeqLength(A));
21+
}
22+
23+
TEST(LongestArithmeticSubsequence, 20_1_15_3_10_5_8) {
24+
vector<int> A = {20, 1, 15, 3, 10, 5, 8};
25+
EXPECT_EQ(4, Solution().longestArithSeqLength(A));
26+
}
27+
28+
TEST(LongestArithmeticSubsequence, 83_20_17_43_52_78_68_45) {
29+
vector<int> A = {83, 20, 17, 43, 52, 78, 68, 45};
30+
EXPECT_EQ(2, Solution().longestArithSeqLength(A));
31+
}

longest-arithmetic-subsequence.cpp

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
* Copyright (c) 2021, Christopher Friedt
3+
*
4+
* SPDX-License-Identifier: MIT
5+
*/
6+
7+
// clang-format off
8+
// name: longest-arithmetic-subsequence
9+
// url: https://leetcode.com/problems/longest-arithmetic-subsequence
10+
// difficulty: 2
11+
// clang-format on
12+
13+
#include <vector>
14+
15+
using namespace std;
16+
17+
class Solution {
18+
public:
19+
int longestArithSeqLength(vector<int> &A) {
20+
/*
21+
Let N be the length of A.
22+
23+
Since A[i] is in [0, 500], then we can consider all differences, d,
24+
to be constrained to the range [-500,500].
25+
26+
let LASL(i,d) == be the longest arithmetic subsequence in the first
27+
i ordered elements where the difference between each element is d.
28+
29+
LASL(0, d) = 0, is a base case for all d
30+
*/
31+
const int N = A.size();
32+
constexpr int M = 500 - (-500) + 1;
33+
constexpr int M_2 = 500;
34+
35+
vector<vector<int>> dp(N, vector<int>(M, 0));
36+
37+
int max_len = 1;
38+
for (int i = 1; i < N; ++i) {
39+
for (int j = 0; j < i; ++j) {
40+
int d = A[i] - A[j];
41+
dp[i][d + M_2] = dp[j][d + M_2] + 1;
42+
max_len = max(max_len, dp[i][d + M_2]);
43+
}
44+
}
45+
46+
return max_len + 1;
47+
}
48+
};

0 commit comments

Comments
 (0)