LeetCode 873. Length of Longest Fibonacci Subsequence
原题链接在这里:https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/
题目:
A sequence X_1, X_2, ..., X_n
is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2}
for alli + 2 <= n
Given a strictly increasing array A
of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A
. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A
by deleting any number of elements (including none) from A
, without changing the order of the remaining elements. For example, [3, 5, 8]
is a subsequence of [3, 4, 5, 6, 7, 8]
.)
Example 1:
Input: [1,2,3,4,5,6,7,8] Output: 5 Explanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18] Output: 3 Explanation: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].
题解:
Take a = A[i] and b = A[j] as first 2 elements, j>i.
Check if A contains A[i]+A[j]. If yes, then a = b, b = a+b, and fibonacci sequence length ++.
Until A doesn't contian (A[i] + A[j]), update the global longest length.
Time Complexity: O(n^2 * logM). n = A.length. M is the largest number in A, since in while loop it grows exponentially, while takes logM.
Space: O(n).
AC Java:
1 class Solution { 2 public int lenLongestFibSubseq(int[] A) { 3 if(A == null || A.length < 3){ 4 return 0; 5 } 6 7 HashSet<Integer> hs = new HashSet<>(); 8 for(int a : A){ 9 hs.add(a); 10 } 11 12 int res = 0; 13 14 int n = A.length; 15 for(int i = 0; i<n-2; i++){ 16 for(int j = i+1; j<n-1; j++){ 17 int a = A[i]; 18 int b = A[j]; 19 int l = 2; 20 while(hs.contains(a+b)){ 21 int temp = a; 22 a = b; 23 b = temp+b; 24 l++; 25 } 26 27 res = Math.max(res, l); 28 } 29 } 30 31 return res > 2 ? res : 0; 32 } 33 }