-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0368-LargestDivisibleSubset.cs
62 lines (54 loc) · 1.63 KB
/
0368-LargestDivisibleSubset.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//-----------------------------------------------------------------------------
// Runtime: 252ms
// Memory Usage: 30.4 MB
// Link: https://leetcode.com/submissions/detail/353312675/
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace LeetCode
{
public class _0368_LargestDivisibleSubset
{
public IList<int> LargestDivisibleSubset(int[] nums)
{
var n = nums.Length;
if (n <= 0) return nums;
Array.Sort(nums);
var length = new int[n];
var prevIndex = new int[n];
for (int i = 0; i < n; i++)
{
length[i] = 1;
prevIndex[i] = -1;
for (int j = 0; j < i; j++)
{
if (nums[i] % nums[j] == 0)
{
if (length[j] + 1 > length[i])
{
length[i] = length[j] + 1;
prevIndex[i] = j;
}
}
}
}
var maxDistance = 0;
var index = -1;
for (int i = 0; i < n; i++)
{
if (length[i] > maxDistance)
{
maxDistance = length[i];
index = i;
}
}
var result = new List<int>();
while (index != -1)
{
result.Add(nums[index]);
index = prevIndex[index];
}
return result;
}
}
}