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; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/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
阅读 974·2019-08-30 10:58
阅读 752·2019-08-29 18:43
阅读 3208·2019-08-29 18:36
阅读 2310·2019-08-29 17:02
阅读 1447·2019-08-29 17:01