Leetcode 873. Length of Longest Fibonacci Subsequence
Given an integer array arr
, return the length of the longest Fib-like subsequence of arr
. If one does not exist, return 0
.
A sequence X1, X2, ..., Xn
is a Fib-like sequence if:
n >= 3
Xi + Xi+1 = Xi+2
for all i + 2 <= n
A subsequence is derived from another sequence arr
by deleting some or none elements without changing the order of the remaining elements. For example, [3, 5, 8]
is a subsequence of [3, 4, 5, 6, 7, 8]
.
arr
?To solve this problem:
dp[i, j]
represents the length of the Fibonacci-like subsequence ending with elements arr[i]
and arr[j]
.(i, j)
and check if there exists an earlier index k
such that arr[k] + arr[i] == arr[j]
. If it exists, update the DP state.O(N^2 log M)
where N
is the length of the array and M
is the maximum number in arr
. The log M
comes from the set operations.O(N^2)
for the DP dictionary and set operations.#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
using namespace std;
int lenLongestFibSubseq(vector<int>& arr) {
unordered_set<int> S(arr.begin(), arr.end());
unordered_map<int, int> dp;
int n = arr.size();
int maxLen = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
int a = arr[i];
int b = arr[j];
int len = 2;
while (S.find(a + b) != S.end()) {
int c = a + b;
a = b;
b = c;
++len;
}
maxLen = max(maxLen, len);
}
}
// We need at least three elements to form a sequence
return maxLen >= 3 ? maxLen : 0;
}
This implementation uses a nested loop to iterate through index pairs and a while-loop to extend the potential Fibonacci subsequence. It ensures to keep track of the longest sequence found and checks if it meets the minimum required length of 3.
Feel free to ask any further questions or specific clarifications!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?