MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / LongestArithmeticSubsequence

Function LongestArithmeticSubsequence

dynamic/longestarithmeticsubsequence.go:10–34  ·  view source on GitHub ↗

LongestArithmeticSubsequence returns the length of the longest arithmetic subsequence

(nums []int)

Source from the content-addressed store, hash-verified

8
9// LongestArithmeticSubsequence returns the length of the longest arithmetic subsequence
10func LongestArithmeticSubsequence(nums []int) int {
11 n := len(nums)
12 if n <= 1 {
13 return n
14 }
15
16 dp := make([]map[int]int, n)
17 for i := range dp {
18 dp[i] = make(map[int]int)
19 }
20
21 maxLength := 1
22
23 for i := 1; i < n; i++ {
24 for j := 0; j < i; j++ {
25 diff := nums[i] - nums[j]
26 dp[i][diff] = dp[j][diff] + 1
27 if dp[i][diff]+1 > maxLength {
28 maxLength = dp[i][diff] + 1
29 }
30 }
31 }
32
33 return maxLength
34}

Callers 1

Calls

no outgoing calls

Tested by 1