703208. Largest Fibonacci Subsequence

Easy

Largest Fibonacci Subsequence

Slug: largest-fibonacci-subsequence2206 Difficulty: Easy Id: 703208 Topic Tags: Arrays, Hash, Fibonacci, Data Structures Company Tags: Facebook

Summary

Given a sequence of integers, the task is to find the longest subsequence that forms a Fibonacci-like series. The Fibonacci series starts with two numbers (usually 0 and 1), and each subsequent number is the sum of the previous two. For example, [0, 1, 1, 2, 3, 5] is a Fibonacci sequence.

Detailed Explanation

The problem can be solved by iterating through the given sequence and maintaining two variables, prev and curr, which represent the last two numbers in the Fibonacci-like series. For each number in the sequence, check if it's equal to the sum of prev and curr. If it is, increment the length of the subsequence and update prev and curr. Otherwise, move on to the next number.

Here's a step-by-step breakdown:

  1. Initialize prev, curr, and the subsequence length to 0.
  2. Iterate through the sequence:
    • For each number, check if it's equal to the sum of prev and curr.
    • If it is, increment the subsequence length and update prev and curr. Otherwise, move on to the next number.
  3. Return the longest Fibonacci-like subsequence found.

Time complexity: O(n), where n is the length of the sequence. Space complexity: O(1), as we only need a few extra variables to store the current state of the subsequence.

Optimized Solutions

Java

View on GeeksforGeeks
public class LargestFibonacciSubsequence {
    public static int largestFibonacciSubsequence(int[] nums) {
        int n = nums.length;
        int prev = 0, curr = 1, maxLength = 0;
        for (int num : nums) {
            if (num == prev + curr) {
                prev = curr;
                curr = num;
                maxLength++;
            } else {
                prev = num;
                curr = num;
                maxLength = 1;
            }
        }
        return maxLength;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.