873. Length of Longest Fibonacci Subsequence

2018/10/06 leetcode 共 1603 字,约 5 分钟

title

problem link

A sequence X_1, X_2, …, X_n is fibonacci-like if:

n >= 3 X_i + X_{i+1} = X_{i+2} for all i + 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].

solution

i, j , k是个fibonacci-like,

i用map存储,查找,查找后i< j 则合法

用一个map存当前结尾的最大fibonacci-like长度,

easy dp

class Solution:
    def lenLongestFibSubseq(self, A: List[int]) -> int:
        index = {A[i]: i for i in range(len(A))}
        longest = {}
        ans = 0
        length = len(A)
        for i in range(length):
            for j in range(i):
                x = A[i] - A[j]
                m = index.get(x)
                if m is not None and m < j:
                    longest[(j, i)] = longest.get((m, j)) + 1 if longest.get((m, j)) is not None else 3
                    ans = max(ans, longest[(j, i)])
                else:
                    continue
        return ans if ans >= 3 else 0

class Solution {
public:
	int lenLongestFibSubseq(vector<int>& A) {

		int N = A.size();
		map<int, int> index, longest;
		for (int i = 0; i < N; i++) {
			index[A[i]] = i;
		}
		int ans = 0;
		for (int k = 0; k < N; k++) {
			for (int j = 0; j < k; j++) {
				if (index.count(A[k]-A[j])) {
					int i = index[A[k] - A[j]];
					if (i < j) {
						if (longest.count(i*N + j)) {
							longest[j*N + k] = longest[i*N + j]+1;
						}
						else {
							longest[j*N + k] = 3;
						}
						ans = max(ans, longest[j*N + k]);

					}
				}
			}
		}
		return ans >= 3 ? ans : 0;
	}
};

Search

    Table of Contents