-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0368-largest-divisible-subset.js
More file actions
48 lines (39 loc) · 1.6 KB
/
0368-largest-divisible-subset.js
File metadata and controls
48 lines (39 loc) · 1.6 KB
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
/**
* Largest Divisible Subset
* Time Complexity: O(N^2)
* Space Complexity: O(N)
*/
var largestDivisibleSubset = function (nums) {
if (nums.length === 0) {
return [];
}
nums.sort((firstNum, secondNum) => firstNum - secondNum);
const dpStates = new Array(nums.length).fill(null).map(() => ({
subsetLength: 1,
previousElementIndex: -1
}));
let overallMaxLength = 1;
let indexOfMaxSubsetEnd = 0;
for (let currentNumberIndex = 0; currentNumberIndex < nums.length; currentNumberIndex++) {
for (let previousNumberIndex = 0; previousNumberIndex < currentNumberIndex; previousNumberIndex++) {
if (nums[currentNumberIndex] % nums[previousNumberIndex] === 0) {
let candidateLength = dpStates[previousNumberIndex].subsetLength + 1;
if (candidateLength > dpStates[currentNumberIndex].subsetLength) {
dpStates[currentNumberIndex].subsetLength = candidateLength;
dpStates[currentNumberIndex].previousElementIndex = previousNumberIndex;
}
}
}
if (dpStates[currentNumberIndex].subsetLength > overallMaxLength) {
overallMaxLength = dpStates[currentNumberIndex].subsetLength;
indexOfMaxSubsetEnd = currentNumberIndex;
}
}
const finalSubset = [];
let currentIndexToTrace = indexOfMaxSubsetEnd;
while (currentIndexToTrace !== -1) {
finalSubset.unshift(nums[currentIndexToTrace]);
currentIndexToTrace = dpStates[currentIndexToTrace].previousElementIndex;
}
return finalSubset;
};