| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 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.LargestDivisibleSubset; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class LargestDivisibleSubsetDynamicProgramming : ILargestDivisibleSubset |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n^2) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public IList<int> LargestDivisibleSubset(int[] nums) |
| 2 | 24 | | { |
| 2 | 25 | | Array.Sort(nums); |
| | 26 | |
|
| 2 | 27 | | var dp = new int[nums.Length]; |
| 2 | 28 | | var prev = new int[nums.Length]; |
| | 29 | |
|
| 2 | 30 | | Array.Fill(dp, 1); |
| 2 | 31 | | Array.Fill(prev, -1); |
| | 32 | |
|
| 2 | 33 | | var maxIndex = 0; |
| | 34 | |
|
| 14 | 35 | | for (var i = 1; i < nums.Length; i++) |
| 5 | 36 | | { |
| 28 | 37 | | for (var j = 0; j < i; j++) |
| 9 | 38 | | { |
| 9 | 39 | | if (nums[i] % nums[j] == 0 && dp[j] + 1 > dp[i]) |
| 8 | 40 | | { |
| 8 | 41 | | dp[i] = dp[j] + 1; |
| | 42 | |
|
| 8 | 43 | | prev[i] = j; |
| 8 | 44 | | } |
| 9 | 45 | | } |
| | 46 | |
|
| 5 | 47 | | if (dp[i] > dp[maxIndex]) |
| 4 | 48 | | { |
| 4 | 49 | | maxIndex = i; |
| 4 | 50 | | } |
| 5 | 51 | | } |
| | 52 | |
|
| 2 | 53 | | var result = new List<int>(); |
| | 54 | |
|
| 8 | 55 | | while (maxIndex != -1) |
| 6 | 56 | | { |
| 6 | 57 | | result.Add(nums[maxIndex]); |
| | 58 | |
|
| 6 | 59 | | maxIndex = prev[maxIndex]; |
| 6 | 60 | | } |
| | 61 | |
|
| 2 | 62 | | result.Reverse(); |
| | 63 | |
|
| 2 | 64 | | return result; |
| 2 | 65 | | } |
| | 66 | | } |