743. Fibonacci-Like Run
A jeweller keeps a tray of beads whose weights are listed in nums. The order of the list is irrelevant and a weight that appears several times counts only once. Lay the distinct weights out in increasing order and pick some of them, keeping that increasing order.
The pick is a cascade if it has at least three beads and every bead after the first two weighs exactly as much as the two beads right before it combined. Return the largest number of beads in any cascade, or 0 if no cascade exists.
Aim for time O(n^2) and space O(n^2), where n is the length of nums.
Example 1
- Input:
- nums = [4,25,6,10,16,26,42,9,3]
- Output:
- 6
- Explanation:
Sorted distinct weights give the cascade 4, 6, 10, 16, 26, 42, where each weight is the sum of the two before it, so the answer is 6.
Example 2
- Input:
- nums = [9,12,15,20]
- Output:
- 0
- Explanation:
No weight equals the sum of two smaller ones, so the answer is 0.
Example 3
- Input:
- nums = [8,2,2,5,3,7,10,17,5]
- Output:
- 4
- Explanation:
Duplicates collapse, then 2, 3, 5, 8 is a cascade of length 4; 7, 10, 17 is shorter, so the answer is 4.
Constraints
1 ≤ nums.length ≤ 1500
1 ≤ nums[i] ≤ 109
The list may be unsorted and may contain repeats.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(n^2)
- Space
- O(n^2)