#3708
Medium Algorithms Longest fibonacci subarray
Array
69.5% acceptance
Feb 24, 2026
53
2
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn longest_subarray(nums: Vec<i32>) -> i32 {
let n = nums.len();
if n < 3 { return n as i32; }
let mut max_len = 2;
let mut len = 2;
for i in 2..n {
if (nums[i - 2] as i64) + (nums[i - 1] as i64) == nums[i] as i64 {
len += 1;
} else {
len = 2;
}
max_len = max_len.max(len);
}
max_len
}
}