Longest Fibonacci Subarray Problem
#3708
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3708.
You are given an array of positive integers nums.
A Fibonacci array is a contiguous sequence whose third and subsequent terms each equal the sum of the two preceding terms.
Return the length of the longest Fibonacci subarray in nums.
Note: Subarrays of length 1 or 2 are always Fibonacci.
Example 1:
Input: nums = [1,1,1,1,2,3,5,1]
Output: 5
Explanation:
The longest Fibonacci subarray is nums[2..6] = [1, 1, 2, 3, 5].
[1, 1, 2, 3, 5] is Fibonacci because 1 + 1 = 2, 1 + 2 = 3, and 2 + 3 = 5.
Example 2:
Input: nums = [5,2,7,9,16]
Output: 5
Explanation:
The longest Fibonacci subarray is nums[0..4] = [5, 2, 7, 9, 16].
[5, 2, 7, 9, 16] is Fibonacci because 5 + 2 = 7, 2 + 7 = 9, and 7 + 9 = 16.
Example 3:
Input: nums = [1000000000,1000000000,1000000000]
Output: 2
Explanation:
The longest Fibonacci subarray is nums[1..2] = [1000000000, 1000000000].
[1000000000, 1000000000] is Fibonacci because its length is 2.
Constraints:
3 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Dynamic Programming
Keep f, the length of the longest Fibonacci subarray ending at the current element. Any two elements form one, so f starts at 2.
For each i >= 2: if nums[i] == nums[i-1] + nums[i-2], the element extends the current run, so f += 1; otherwise the run breaks and f resets to 2. The answer is the largest f seen.
Complexity: O(n) time and O(1) space.
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
n = len(nums)
ans = f = 2
for i in range(2, n):
if nums[i] == nums[i - 1] + nums[i - 2]:
f = f + 1
ans = max(ans, f)
else:
f = 2
return ans