-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution1027.cs
45 lines (37 loc) · 1.04 KB
/
Solution1027.cs
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
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution1027
{
/// <summary>
/// 1027. Longest Arithmetic Subsequence - Medium
/// <a href="https://leetcode.com/problems/longest-arithmetic-subsequence</a>
/// </summary>
public int LongestArithSeqLength(int[] nums)
{
int n = nums.Length;
if (n <= 1) {
return n;
}
var dp = new Dictionary<int, int>[n];
int maxLength = 2;
for (int i = 0; i < n; i++)
{
dp[i] = [];
for (int j = 0; j < i; j++)
{
int diff = nums[i] - nums[j];
if (dp[j].ContainsKey(diff))
{
dp[i][diff] = dp[j][diff] + 1;
}
else
{
dp[i][diff] = 2; // Start new sequence with nums[j] and nums[i]
}
maxLength = Math.Max(maxLength, dp[i][diff]);
}
}
return maxLength;
}
}