Skip to content

Commit 5409641

Browse files
committedFeb 23, 2025
Add solution #368
1 parent 0d0eef9 commit 5409641

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,7 @@
289289
363|[Max Sum of Rectangle No Larger Than K](./0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard|
290290
365|[Water and Jug Problem](./0365-water-and-jug-problem.js)|Medium|
291291
367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy|
292+
368|[Largest Divisible Subset](./0368-largest-divisible-subset.js)|Medium|
292293
371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium|
293294
372|[Super Pow](./0372-super-pow.js)|Medium|
294295
374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium|
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 368. Largest Divisible Subset
3+
* https://leetcode.com/problems/largest-divisible-subset/
4+
* Difficulty: Medium
5+
*
6+
* Given a set of distinct positive integers nums, return the largest subset answer such that
7+
* every pair (answer[i], answer[j]) of elements in this subset satisfies:
8+
* - answer[i] % answer[j] == 0, or
9+
* - answer[j] % answer[i] == 0
10+
*
11+
* If there are multiple solutions, return any of them.
12+
*/
13+
14+
/**
15+
* @param {number[]} nums
16+
* @return {number[]}
17+
*/
18+
var largestDivisibleSubset = function(nums) {
19+
nums.sort((a, b) => a - b);
20+
const dp = nums.map(() => [1, -1]);
21+
let max = 0;
22+
for (let i = 1; i < nums.length; i++) {
23+
for (let j = 0; j < i; j++) {
24+
if (nums[i] % nums[j] === 0 && dp[j][0] + 1 > dp[i][0]) {
25+
dp[i] = [dp[j][0] + 1, j], dp[i][0] > dp[max][0] && (max = i);
26+
}
27+
}
28+
}
29+
30+
const result = [];
31+
for (let i = max; i >= 0; i = dp[i][1]) {
32+
result.unshift(nums[i]);
33+
}
34+
35+
return result;
36+
};

0 commit comments

Comments
 (0)
Please sign in to comment.