Search

[873] Length of Longest Fibonacci Subsequence

태그
Dynamic Programming
HashMap
Tier
Medium
날짜
2025/03/15

Question

A sequence x1, x2, ..., xn is Fibonacci-like if:
n >= 3
xi + xi+1 == xi+2 for all i + 2 <= n
Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0.
subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].
Example 1:
Input: arr = [1,2,3,4,5,6,7,8] Output: 5 Explanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Plain Text
복사
Example 2:
Input: arr = [1,3,7,11,12,14,18] Output: 3 Explanation:The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].
Plain Text
복사

My Answer

# testcase 26/57 # Fail class Solution: def lenLongestFibSubseq(self, arr: List[int]) -> int: n = len(arr) max_length = 0 for i in range(n): for j in range(i+1,n): x = arr[i] y = arr[j] length = 2 while x+y in arr: next_num = x+y x = y y = next_num length+=1 max_length = max(max_length,length) return max_length
Python
복사

Optimized Version

class Solution: def lenLongestFibSubseq(self, arr: List[int]) -> int: index = {num: i for i, num in enumerate(arr)} # 각 숫자의 인덱스를 저장하는 딕셔너리 dp = {} # DP 테이블 (i, j) -> subsequence 길이 max_length = 0 n = len(arr) for j in range(n): for i in range(j): x, y = arr[i], arr[j] prev = x + y if prev in index and index[prev] > j: k = index[prev] # 다음 숫자의 인덱스 dp[(j, k)] = dp.get((i, j), 2) + 1 # 기존 subsequence 길이 + 1 max_length = max(max_length, dp[(j, k)]) return max_length if max_length >= 3 else 0 # 길이가 3 이상일 때만 유효
Python
복사