[LeetCode] Longest Fibonacci Subarray

3708. Longest Fibonacci Subarray

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int longestSubarray(vector<int>& nums) {
long long res = 0, now = 2;
for(int i = 0; i + 2 < nums.size(); i++) {
long long expect = nums[i] + nums[i+1];
now = nums[i+2] == expect ? now + 1 : 2;
res = max(res, now);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/10/13/PS/LeetCode/longest-fibonacci-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.