| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | | 3 | | // All Rights Reserved. |
| | | 4 | | // -------------------------------------------------------------------------------- |
| | | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | | 9 | | // known as Yevhenii Yeriemeieiv). |
| | | 10 | | // -------------------------------------------------------------------------------- |
| | | 11 | | |
| | | 12 | | namespace LeetCode.Algorithms.LengthOfLongestFibonacciSubsequence; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class LengthOfLongestFibonacciSubsequenceDynamicProgramming : ILengthOfLongestFibonacciSubsequence |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n^2) |
| | | 19 | | /// Space complexity - O(n^2) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="arr"></param> |
| | | 22 | | /// <returns></returns> |
| | | 23 | | public int LenLongestFibSubseq(int[] arr) |
| | 2 | 24 | | { |
| | 2 | 25 | | var dictionary = new Dictionary<int, int>(); |
| | | 26 | | |
| | 34 | 27 | | for (var i = 0; i < arr.Length; i++) |
| | 15 | 28 | | { |
| | 15 | 29 | | dictionary[arr[i]] = i; |
| | 15 | 30 | | } |
| | | 31 | | |
| | 2 | 32 | | var dp = new int[arr.Length, arr.Length]; |
| | | 33 | | |
| | 2 | 34 | | var result = 0; |
| | | 35 | | |
| | 34 | 36 | | for (var i = 0; i < arr.Length; i++) |
| | 15 | 37 | | { |
| | 128 | 38 | | for (var j = i + 1; j < arr.Length; j++) |
| | 49 | 39 | | { |
| | 49 | 40 | | dp[i, j] = 2; |
| | | 41 | | |
| | 49 | 42 | | var potentialPrev = arr[j] - arr[i]; |
| | | 43 | | |
| | 49 | 44 | | if (!dictionary.TryGetValue(potentialPrev, out var k) || k >= i) |
| | 34 | 45 | | { |
| | 34 | 46 | | continue; |
| | | 47 | | } |
| | | 48 | | |
| | 15 | 49 | | dp[i, j] = dp[k, i] + 1; |
| | | 50 | | |
| | 15 | 51 | | result = Math.Max(result, dp[i, j]); |
| | 15 | 52 | | } |
| | 15 | 53 | | } |
| | | 54 | | |
| | 2 | 55 | | return result >= 3 ? result : 0; |
| | 2 | 56 | | } |
| | | 57 | | } |