Problem
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].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
class Solution { public int lenLongestFibSubseq(int[] A) { Setset = new HashSet<>(); for (int a: A) set.add(a); int max = 2; for (int i = 0; i < A.length-1; i++) { for (int j = i+1; j < A.length; j++) { int a1 = A[i], a2 = A[j]; int curMax = 2; while (set.contains(a1+a2)) { curMax++; int temp = a1; a1 = a2; a2 = temp+a2; } max = Math.max(max, curMax); } } return max == 2 ? 0 : max; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/72670.html
摘要:難度題意是求最長無重復(fù)子串給出一個(gè)字符串從所有子串中找出最長且沒有重復(fù)字母的子串的長度我的解法是以為例使用一個(gè)記錄當(dāng)前子串遇到的所有字符用一個(gè)游標(biāo)從頭開始讀取字符加入到中如果碰到了重復(fù)字符遇到了重復(fù)則從當(dāng)前子串的頭部的字符開始將該字符從中移 Longest Substring Without Repeating CharactersGiven a string, find the le...
Problem Suppose we abstract our file system by a string in the following manner: The string dirntsubdir1ntsubdir2nttfile.ext represents: dir subdir1 subdir2 file.ext The directory dir ...
摘要:遞歸法復(fù)雜度時(shí)間空間思路因?yàn)橐易铋L的連續(xù)路徑,我們在遍歷樹的時(shí)候需要兩個(gè)信息,一是目前連起來的路徑有多長,二是目前路徑的上一個(gè)節(jié)點(diǎn)的值。代碼判斷當(dāng)前是否連續(xù)返回當(dāng)前長度,左子樹長度,和右子樹長度中較大的那個(gè) Binary Tree Longest Consecutive Sequence Given a binary tree, find the length of the lon...
摘要:原問題我的沙雕解法無重復(fù)字母存在重復(fù)字母挨打最暴力的無腦解法,耗時(shí)。。。 原問題 Given a string, find the length of the?longest substring?without repeating characters. Example 1: Input: abcabcbb Output: 3 Explanation: The answer is a...
摘要:解題思路本題借助實(shí)現(xiàn)。如果字符未出現(xiàn)過,則字符,如果字符出現(xiàn)過,則維護(hù)上次出現(xiàn)的遍歷的起始點(diǎn)。注意點(diǎn)每次都要更新字符的位置最后返回時(shí),一定要考慮到從到字符串末尾都沒有遇到重復(fù)字符的情況,所欲需要比較下和的大小。 Longest Substring Without Repeating CharactersGiven a string, find the length of the lon...
閱讀 2310·2021-11-25 09:43
閱讀 2946·2019-08-30 15:52
閱讀 1897·2019-08-30 15:44
閱讀 985·2019-08-30 10:58
閱讀 764·2019-08-29 18:43
閱讀 3220·2019-08-29 18:36
閱讀 2321·2019-08-29 17:02
閱讀 1461·2019-08-29 17:01