LeetCode 873: Length of Longest Fibonacci Subsequence

Problem Description

Explanation:

To solve this problem, we can use dynamic programming. We can iterate over pairs of numbers in the array and try to extend the Fibonacci-like subsequence as much as possible. We can keep track of the lengths of the Fibonacci-like subsequences ending at each pair of numbers. By considering each pair as the last two elements in the subsequence, we can calculate the length of the subsequence ending at those pairs.

  • We maintain a hashmap to store the index of each element in the input array for quick lookups.
  • We iterate over all pairs (A, B) in the array and try to extend the Fibonacci-like subsequence by checking if the next element (A + B) is also present in the array.
  • If (A + B) is found in the array, we update the length of the Fibonacci-like subsequence ending at (A, B) by adding 1 to the length of the subsequence ending at (B, A + B).
  • We keep track of the maximum length of Fibonacci-like subsequences found during the iteration.

Time Complexity: O(n^2) where n is the length of the input array. Space Complexity: O(n) where n is the length of the input array.

:

Solutions

class Solution {
    public int lenLongestFibSubseq(int[] arr) {
        int n = arr.length;
        Map<Integer, Integer> index = new HashMap<>();
        for (int i = 0; i < n; i++) {
            index.put(arr[i], i);
        }
        
        Map<Integer, Integer> dp = new HashMap<>();
        int maxLen = 0;
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i; j++) {
                int k = index.getOrDefault(arr[i] - arr[j], -1);
                if (k >= 0 && k < j) {
                    int len = dp.getOrDefault(k * n + j, 2) + 1;
                    dp.put(j * n + i, len);
                    maxLen = Math.max(maxLen, len);
                }
            }
        }
        
        return maxLen;
    }
}

Loading editor...