-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path113.go
More file actions
44 lines (39 loc) · 899 Bytes
/
113.go
File metadata and controls
44 lines (39 loc) · 899 Bytes
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
func lenLongestFibSubseq(arr []int) int {
n := len(arr)
maxLen := 0
// dp[prev][curr] stores length of Fibonacci sequence ending at indexes prev, curr
dp := make([][]int, n)
for i := range dp {
dp[i] = make([]int, n)
}
// Map each value to its index for O(1) lookup
valToIdx := make(map[int]int)
for i, num := range arr {
valToIdx[num] = i
}
// Fill dp array
for curr := 0; curr < n; curr++ {
for prev := 0; prev < curr; prev++ {
diff := arr[curr] - arr[prev]
prevIdx, exists := valToIdx[diff]
// Update dp if valid Fibonacci sequence possible
if exists && diff < arr[prev] {
dp[prev][curr] = dp[prevIdx][prev] + 1
} else {
dp[prev][curr] = 2
}
maxLen = max(maxLen, dp[prev][curr])
}
}
// Return 0 if no sequence of length > 2 found
if maxLen > 2 {
return maxLen
}
return 0
}
func max(a, b int) int {
if a > b {
return a
}
return b
}