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; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/72670.html
摘要:難度題意是求最長無重復子串給出一個字符串從所有子串中找出最長且沒有重復字母的子串的長度我的解法是以為例使用一個記錄當前子串遇到的所有字符用一個游標從頭開始讀取字符加入到中如果碰到了重復字符遇到了重復則從當前子串的頭部的字符開始將該字符從中移 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 ...
摘要:遞歸法復雜度時間空間思路因為要找最長的連續路徑,我們在遍歷樹的時候需要兩個信息,一是目前連起來的路徑有多長,二是目前路徑的上一個節點的值。代碼判斷當前是否連續返回當前長度,左子樹長度,和右子樹長度中較大的那個 Binary Tree Longest Consecutive Sequence Given a binary tree, find the length of the lon...
摘要:原問題我的沙雕解法無重復字母存在重復字母挨打最暴力的無腦解法,耗時。。。 原問題 Given a string, find the length of the?longest substring?without repeating characters. Example 1: Input: abcabcbb Output: 3 Explanation: The answer is a...
摘要:解題思路本題借助實現。如果字符未出現過,則字符,如果字符出現過,則維護上次出現的遍歷的起始點。注意點每次都要更新字符的位置最后返回時,一定要考慮到從到字符串末尾都沒有遇到重復字符的情況,所欲需要比較下和的大小。 Longest Substring Without Repeating CharactersGiven a string, find the length of the lon...
閱讀 2247·2021-11-25 09:43
閱讀 2934·2019-08-30 15:52
閱讀 1885·2019-08-30 15:44
閱讀 975·2019-08-30 10:58
閱讀 754·2019-08-29 18:43
閱讀 3209·2019-08-29 18:36
閱讀 2310·2019-08-29 17:02
閱讀 1447·2019-08-29 17:01