Problem Description
Given a strictly increasing array arr of positive integers, find the length of the longest subsequence that is Fibonacci-like. A Fibonacci-like sequence has at least 3 numbers and each subsequent number is the sum of the previous two. If no such subsequence exists, return 0.
Key Insights
- The array is strictly increasing, which enables binary search or hash mapping techniques.
- We can use dynamic programming to record the length of the Fibonacci-like sequence ending with any two numbers.
- A hash map is used to quickly determine if a needed previous number exists in the sequence.
- The recurrence relation: if arr[k] = arr[j] - arr[i] exists (with k < i) then dp[i][j] = dp[k][i] + 1, else start with length 2 for pairs.
Space and Time Complexity
Time Complexity: O(n^2)
Space Complexity: O(n^2) (in the worst-case scenario for the DP table and O(n) for the hash map)
Solution
We solve this problem using dynamic programming along with a hash map. The idea is to maintain a 2D DP table where dp[i][j] represents the length of the Fibonacci-like sequence ending with arr[i] and arr[j]. For every pair (i, j), we check if there exists an index k such that arr[k] equals arr[j] - arr[i] and k < i. If such an index exists, then we can extend the sequence represented by dp[k][i] by one, thereby updating dp[i][j] to dp[k][i] + 1. We traverse through all possible pairs and update our result accordingly. Finally, if the longest sequence found has a length of 2 or less (which means no valid sequence was found), we return 0; otherwise, we return the maximum length found.