Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created February 27, 2025 19:00
Show Gist options
  • Save tatsuyax25/a001cbd3af7c26a8521abf5ebd67c253 to your computer and use it in GitHub Desktop.
Save tatsuyax25/a001cbd3af7c26a8521abf5ebd67c253 to your computer and use it in GitHub Desktop.
A sequence x1, x2, ..., xn is Fibonacci-like if: n >= 3 xi + xi+1 == xi+2 for all i + 2 <= n Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one do
/**
* @param {number[]} arr
* @return {number}
*/
var lenLongestFibSubseq = function(arr) {
const n = arr.length;
if (n < 3) return 0;
const indexMap = new Map();
for (let i = 0; i < n; i++) {
indexMap.set(arr[i], i);
}
const dp = new Map();
let maxLength = 0;
// Iterate over all pairs (i, j) where i < j.
for (let j = 0; j < n; j++) {
for (let i = 0; i < j; i++) {
const x = arr[i];
const y = arr[j];
const z = x + y;
// Check if z is in the array.
if (indexMap.has(z)) {
const k = indexMap.get(z);
const key = `${y},${z}`; // Create a unique key for the pair (y, z).
const prevKey = `${x},${y}`; // Create a unique key for the pair (x, y).
const newLength = (dp.get(prevKey) || 2) + 1;
dp.set(key, newLength);
maxLength = Math.max(maxLength, newLength);
}
}
}
return maxLength >= 3 ? maxLength : 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment