101 Logo
onenoughtone

Problem Statement

Fibonacci Subsequence Finder

You are a data scientist working for a financial research firm. The firm is studying patterns in stock prices and believes that Fibonacci sequences might be useful for predicting future trends. Your task is to analyze historical stock price data to find the longest Fibonacci-like pattern.

Given a strictly increasing array of positive integers arr, your task is to find the length of the longest subsequence that forms a Fibonacci sequence.

A subsequence is derived from an array by deleting some or no elements without changing the order of the remaining elements. A Fibonacci sequence is a sequence where each number is the sum of the two preceding ones, starting from 0 and 1. For this problem, we'll consider sequences that start with any two positive integers.

Examples

Example 1:

Input: arr = [1, 2, 3, 4, 5, 6, 7, 8]
Output: 5
Explanation: The longest subsequence that forms a Fibonacci sequence is [1, 2, 3, 5, 8].

Example 2:

Input: arr = [1, 3, 7, 11, 12, 14, 18]
Output: 3
Explanation: The longest subsequence that forms a Fibonacci sequence is [1, 11, 12], [3, 11, 14] or [7, 11, 18].

Example 3:

Input: arr = [1, 2, 4, 8, 16]
Output: 2
Explanation: There is no Fibonacci subsequence longer than 2 elements. Any two elements can form a valid Fibonacci subsequence.

Constraints

  • 3 <= arr.length <= 1000
  • 1 <= arr[i] < arr[i+1] <= 10^9

Problem Breakdown

To solve this problem, we need to:

  1. A Fibonacci sequence of length at least 3 is uniquely determined by its first two elements.
  2. Since the array is strictly increasing, we can use dynamic programming to find the longest Fibonacci subsequence.
  3. We can use a hash map to quickly check if a specific value exists in the array.
  4. For each pair of elements (arr[i], arr[j]) where i < j, we can check if there's a Fibonacci sequence starting with these two elements.
ProblemSolutionCode
101 Logo
onenoughtone