Skip to content

Commit 00a019f

Browse files
Sync LeetCode submission Runtime - 239 ms (72.40%), Memory - 385.4 MB (12.61%)
1 parent 20eb300 commit 00a019f

2 files changed

Lines changed: 57 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<p>Given an array <code>nums</code> of integers, return <em>the length of the longest arithmetic subsequence in</em> <code>nums</code>.</p>
2+
3+
<p><strong>Note</strong> that:</p>
4+
5+
<ul>
6+
<li>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</li>
7+
<li>A sequence <code>seq</code> is arithmetic if <code>seq[i + 1] - seq[i]</code> are all the same value (for <code>0 &lt;= i &lt; seq.length - 1</code>).</li>
8+
</ul>
9+
10+
<p>&nbsp;</p>
11+
<p><strong class="example">Example 1:</strong></p>
12+
13+
<pre>
14+
<strong>Input:</strong> nums = [3,6,9,12]
15+
<strong>Output:</strong> 4
16+
<strong>Explanation: </strong> The whole array is an arithmetic sequence with steps of length = 3.
17+
</pre>
18+
19+
<p><strong class="example">Example 2:</strong></p>
20+
21+
<pre>
22+
<strong>Input:</strong> nums = [9,4,7,2,10]
23+
<strong>Output:</strong> 3
24+
<strong>Explanation: </strong> The longest arithmetic subsequence is [4,7,10].
25+
</pre>
26+
27+
<p><strong class="example">Example 3:</strong></p>
28+
29+
<pre>
30+
<strong>Input:</strong> nums = [20,1,15,3,10,5,8]
31+
<strong>Output:</strong> 4
32+
<strong>Explanation: </strong> The longest arithmetic subsequence is [20,15,10,5].
33+
</pre>
34+
35+
<p>&nbsp;</p>
36+
<p><strong>Constraints:</strong></p>
37+
38+
<ul>
39+
<li><code>2 &lt;= nums.length &lt;= 1000</code></li>
40+
<li><code>0 &lt;= nums[i] &lt;= 500</code></li>
41+
</ul>
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
public:
3+
int longestArithSeqLength(vector<int>& nums) {
4+
int n = nums.size();
5+
int ans = 0;
6+
for (int d=-500; d<=500; d++) {
7+
vector<int> dp(2001, 0);
8+
for (int num : nums) {
9+
num += 500;
10+
dp[num] = dp[num - d] + 1;
11+
ans = max(ans, dp[num]);
12+
}
13+
}
14+
return ans;
15+
}
16+
};

0 commit comments

Comments
 (0)