File tree 1 file changed +40
-0
lines changed
1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Problem Number: 368
2
+
3
+ // Largest Divisible Subset.
4
+
5
+ class Solution {
6
+ public List <Integer > largestDivisibleSubset (int [] nums ) {
7
+ final int n = nums .length ;
8
+ List <Integer > ans = new ArrayList <>();
9
+
10
+ int [] sizeEndsAt = new int [n ];
11
+
12
+ int [] prevIndex = new int [n ];
13
+ int maxSize = 0 ;
14
+ int index = -1 ;
15
+
16
+ Arrays .fill (sizeEndsAt , 1 );
17
+ Arrays .fill (prevIndex , -1 );
18
+ Arrays .sort (nums );
19
+
20
+ for (int i = 0 ; i < n ; ++i ) {
21
+ for (int j = i - 1 ; j >= 0 ; --j )
22
+ if (nums [i ] % nums [j ] == 0 && sizeEndsAt [i ] < sizeEndsAt [j ] + 1 ) {
23
+ sizeEndsAt [i ] = sizeEndsAt [j ] + 1 ;
24
+ prevIndex [i ] = j ;
25
+ }
26
+
27
+ if (maxSize < sizeEndsAt [i ]) {
28
+ maxSize = sizeEndsAt [i ];
29
+ index = i ;
30
+ }
31
+ }
32
+
33
+ while (index != -1 ) {
34
+ ans .add (nums [index ]);
35
+ index = prevIndex [index ];
36
+ }
37
+
38
+ return ans ;
39
+ }
40
+ }
You can’t perform that action at this time.
0 commit comments