diff options
author | Jack Sangdahl <[email protected]> | 2025-03-10 00:36:13 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-03-10 00:36:13 -0600 |
commit | 7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch) | |
tree | eb7a24ee2067f92245c57bb118e85a1baf15df50 /other/longest_arithmetic_subseq.cpp | |
parent | 5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff) | |
download | leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip |
chore: move cpp and rust code to directory
Diffstat (limited to 'other/longest_arithmetic_subseq.cpp')
-rw-r--r-- | other/longest_arithmetic_subseq.cpp | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/other/longest_arithmetic_subseq.cpp b/other/longest_arithmetic_subseq.cpp new file mode 100644 index 0000000..5cc91a7 --- /dev/null +++ b/other/longest_arithmetic_subseq.cpp @@ -0,0 +1,37 @@ +// 1027. Longest Arithmetic Subsequence +#include "leetcode.h" + +/* + * given an array 'nums' of integers, return the length of the longest + * arithmetic subsequence in 'nums'. note that + * - a subsequence is an array that can be derived from another array by + * deleting some or no elements without changing the order of the remaining + * elements. + * - a sequence 'seq' is arithmetic if 'seq[i + 1] - seq[i]' are all the same + * value (for '0 <= i < seq.len() - 1') + */ + +class Solution { +public: + int longestArithmeticSeqLength(vector<int> &nums) { + int n = nums.size(), ans = 0; + vvd dp(n, vector<int>(n, 1)); + for (int i = 1; i < n - 1; ++i) + for (int j = i + 1; j < n; ++j) { + for (int k = i - 1; k >= 0; k--) + if (nums[i] - nums[k] == nums[j] - nums[i]) + dp[i][j] = max(dp[i][j], dp[k][i] + 1); + ans = max(ans, dp[i][j]); + } + return ans + 1; + } +}; + +int main() { + Solution obj; + vector<int> n1 = {3, 6, 9, 12}, n2 = {9, 4, 7, 2, 10}, + n3 = {20, 1, 15, 3, 10, 5, 8}; + printf("%d\n", obj.longestArithmeticSeqLength(n1)); // expect: 4 + printf("%d\n", obj.longestArithmeticSeqLength(n2)); // expect: 3 + printf("%d\n", obj.longestArithmeticSeqLength(n3)); // expect: 4 +} |