873. Length of Longest Fibonacci Subsequence #1368
-
Topics: A sequence
Given a strictly increasing array A subsequence is derived from another sequence Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the length of the longest Fibonacci-like subsequence in a strictly increasing array. A Fibonacci-like sequence is defined such that each element after the first two is the sum of the two preceding ones. Approach
Let's implement this solution in PHP: 873. Length of Longest Fibonacci Subsequence <?php
/**
* @param Integer[] $arr
* @return Integer
*/
function lenLongestFibSubseq($arr) {
$n = count($arr);
if ($n < 3) return 0;
$valueMap = array();
// Store indices of values in arr for quick lookup
foreach ($arr as $i => $val) {
$valueMap[$val] = $i;
}
$max = 0;
$dp = array_fill(0, $n, array_fill(0, $n, 2));
// Dynamic programming approach
for ($k = 0; $k < $n; $k++) {
for ($j = 0; $j < $k; $j++) {
$diff = $arr[$k] - $arr[$j]; // Previous term in Fibonacci sequence
if (isset($valueMap[$diff])) {
$i = $valueMap[$diff];
if ($i < $j) {
$dp[$j][$k] = $dp[$i][$j] + 1;
if ($dp[$j][$k] > $max) {
$max = $dp[$j][$k];
}
}
}
}
}
return $max >= 3 ? $max : 0;
}
// Example test cases
$arr1 = [1,2,3,4,5,6,7,8];
echo lenLongestFibSubseq($arr1) . "\n"; // Output: 5
$arr2 = [1,3,7,11,12,14,18];
echo lenLongestFibSubseq($arr2) . "\n"; // Output: 3
?> Explanation:
This approach efficiently checks all possible pairs and uses dynamic programming to build up the solution, resulting in an O(n^2) time complexity and O(n^2) space complexity, which is feasible for the given problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to find the length of the longest Fibonacci-like subsequence in a strictly increasing array. A Fibonacci-like sequence is defined such that each element after the first two is the sum of the two preceding ones.
Approach
Dynamic Programming (DP) with Hash Map:
dp[j][k]
represents the length of the longest Fibonacci-like subsequence ending with elements at indicesj
andk
. Initialize all elements to 2 since any two elements can…