LongestArithmeticSubsequence returns the length of the longest arithmetic subsequence
(nums []int)
| 8 | |
| 9 | // LongestArithmeticSubsequence returns the length of the longest arithmetic subsequence |
| 10 | func 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 | } |
no outgoing calls