Skip to content

Commit 2468b9a

Browse files
authored
Update 368-largest-divisible-subset.js
1 parent d48e868 commit 2468b9a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

368-largest-divisible-subset.js

+34
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,37 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[]}
4+
*/
5+
const largestDivisibleSubset = function(nums) {
6+
const n = nums.length;
7+
if(n === 0 || n === 1) return nums
8+
let maxSize = 0;
9+
const dp = Array(n).fill(1)
10+
nums.sort((a, b) => a - b)
11+
for(let i = 1; i < n; i++) {
12+
for(let j = i - 1; j >= 0; j--) {
13+
if(nums[i] % nums[j] === 0) {
14+
const tmp = dp[j] + 1
15+
if(tmp > dp[i]) dp[i] = tmp
16+
}
17+
}
18+
if(dp[i] > maxSize) maxSize = dp[i]
19+
}
20+
const res = []
21+
let pivot = 0
22+
for(let i = n - 1; i >= 0; i--) {
23+
if(dp[i] === maxSize && (pivot % nums[i] === 0)) {
24+
pivot = nums[i]
25+
maxSize--
26+
res.push(nums[i])
27+
}
28+
}
29+
30+
return res
31+
};
32+
33+
// another
34+
135
/**
236
* @param {number[]} nums
337
* @return {number[]}

0 commit comments

Comments
 (0)