Length of Longest Fibonacci Subsequence - Problem
Imagine you're a mathematician studying Fibonacci-like sequences within arrays of numbers. A sequence is considered Fibonacci-like if it has at least 3 elements and each element (starting from the third) equals the sum of the two preceding elements.
Your mission: Given a strictly increasing array of positive integers, find the length of the longest Fibonacci-like subsequence. If no such subsequence exists, return 0.
Key Rules:
- A Fibonacci-like sequence needs at least 3 elements
- For any valid sequence [a, b, c, d, ...]: a + b = c, b + c = d, etc.
- You can skip elements in the array (subsequence property)
- Order must be preserved
Example: In array [1, 2, 3, 4, 5, 8], the subsequence [1, 2, 3, 5, 8] is Fibonacci-like because 1+2=3, 2+3=5, 3+5=8. Its length is 5.
Input & Output
example_1.py — Basic Fibonacci Sequence
$
Input:
[1,2,3,4,5,8]
›
Output:
5
💡 Note:
The longest Fibonacci-like subsequence is [1,2,3,5,8] with length 5. We have 1+2=3, 2+3=5, 3+5=8.
example_2.py — Multiple Sequences
$
Input:
[1,3,7,11,12,14,18]
›
Output:
3
💡 Note:
The longest Fibonacci-like subsequence has length 3: [1,11,12] because 1+11=12. Another valid sequence is [3,11,14] with 3+11=14.
example_3.py — No Valid Sequence
$
Input:
[1,2,4,8,16]
›
Output:
0
💡 Note:
No Fibonacci-like subsequence exists. Each element is double the previous (geometric sequence), but not sum-based (Fibonacci-like).
Constraints
- 3 ≤ arr.length ≤ 1000
- 1 ≤ arr[i] < arr[i + 1] ≤ 109
- Array is strictly increasing
- All elements are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Catalog Notes
Create an index of all available note frequencies for quick lookup
2
Test Harmonies
For each pair of notes, check if their harmonic sum exists in our catalog
3
Extend Progressions
When a harmonic sum is found, extend the progression and track its length
4
Find Longest
Remember the longest harmonic progression discovered
Key Takeaway
🎯 Key Insight: Just like musical harmonies, each Fibonacci-like sequence is uniquely identified by its last two 'notes' - this allows us to efficiently track and extend sequences using dynamic programming!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code