Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4990812

Browse files
committed
873
1 parent 1f3b109 commit 4990812

File tree

1 file changed

+42
-0
lines changed
  • Medium/873. Length of Longest Fibonacci Subsequence

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
class Solution
3+
{
4+
/**
5+
* @param Integer[] $arr
6+
* @return Integer
7+
*/
8+
public function lenLongestFibSubseq($arr)
9+
{
10+
$n = count($arr);
11+
$indexMap = array_flip($arr);
12+
$dp = [];
13+
$maxLength = 0;
14+
15+
for ($j = 0; $j < $n; $j++) {
16+
for ($i = 0; $i < $j; $i++) {
17+
$x = $arr[$i];
18+
$y = $arr[$j];
19+
$z = $x + $y;
20+
21+
if (isset($indexMap[$z])) {
22+
$k = $indexMap[$z];
23+
24+
if (! isset($dp["$i,$j"])) {
25+
$dp["$i,$j"] = 2;
26+
}
27+
28+
$dp["$j,$k"] = $dp["$i,$j"] + 1;
29+
$maxLength = max($maxLength, $dp["$j,$k"]);
30+
}
31+
}
32+
}
33+
34+
return $maxLength >= 3 ? $maxLength : 0;
35+
}
36+
}
37+
38+
$arr = [1, 3, 7, 11, 12, 14, 18];
39+
40+
$solution = new Solution();
41+
42+
echo $solution->lenLongestFibSubseq($arr); // Output: 4

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /