Leetcode 873: Length of Longest Fibonacci Subsequence

grid47
grid47
Exploring patterns and algorithms
Aug 11, 2024 5 min read

A sequence is called Fibonacci-like if for all indices i, the following condition holds: xi + xi+1 == xi+2. You are given a strictly increasing sequence of positive integers, and your task is to find the length of the longest subsequence that is Fibonacci-like. If no such subsequence exists, return 0.
Problem
Approach
Steps
Complexity
Input: The input consists of a sequence arr of strictly increasing positive integers.
Example: Input: arr = [2, 4, 6, 10, 16, 26, 42]
Constraints:
• 3 <= arr.length <= 1000
• 1 <= arr[i] < arr[i + 1] <= 10^9
Output: Return the length of the longest Fibonacci-like subsequence. If no such subsequence exists, return 0.
Example: Output: 6
Constraints:
• The output should be a single integer indicating the length of the longest Fibonacci-like subsequence.
Goal: The goal is to find the longest subsequence of arr that satisfies the Fibonacci-like property.
Steps:
• Iterate over all pairs of elements arr[i] and arr[j], with i < j, and try to extend the sequence by checking if arr[i] + arr[j] exists in arr.
• Track the length of the Fibonacci-like subsequences found using dynamic programming or hash-based methods.
• Return the length of the longest Fibonacci-like subsequence.
Goal: The input sequence is strictly increasing, and the elements lie within the specified range.
Steps:
• 3 <= arr.length <= 1000
• 1 <= arr[i] < arr[i + 1] <= 10^9
Assumptions:
• The input array is strictly increasing.
• A subsequence is obtained by removing some or none of the elements from the original array while maintaining the relative order.
Input: Input: arr = [2, 4, 6, 10, 16, 26, 42]
Explanation: The longest Fibonacci-like subsequence is [2, 4, 6, 10, 16, 26] which has length 6.

Input: Input: arr = [1, 2, 3, 5, 8, 13, 21]
Explanation: The longest Fibonacci-like subsequence is [1, 2, 3, 5, 8, 13] which has length 6.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus