4003. Longest Fibonacci Subarray
Medium
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 <= 105
1 <= nums[i] <= 109
// Add your C++ solution here
class Solution {
public int longestSubarray(int[] nums) {
int n = nums.length;
int maxi = 2, current = 2;
int a = nums[0], b = nums[1];
for (int i = 2; i < n; i++) {
if (a + b != nums[i]) {
a = b;
b = nums[i];
current = 2;
} else {
current++;
maxi = Math.max(maxi, current);
a = b;
b = nums[i];
}
}
return maxi;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20