File tree 2 files changed +37
-0
lines changed
2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change 289
289
363|[ Max Sum of Rectangle No Larger Than K] ( ./0363-max-sum-of-rectangle-no-larger-than-k.js ) |Hard|
290
290
365|[ Water and Jug Problem] ( ./0365-water-and-jug-problem.js ) |Medium|
291
291
367|[ Valid Perfect Square] ( ./0367-valid-perfect-square.js ) |Easy|
292
+ 368|[ Largest Divisible Subset] ( ./0368-largest-divisible-subset.js ) |Medium|
292
293
371|[ Sum of Two Integers] ( ./0371-sum-of-two-integers.js ) |Medium|
293
294
372|[ Super Pow] ( ./0372-super-pow.js ) |Medium|
294
295
374|[ Guess Number Higher or Lower] ( ./0374-guess-number-higher-or-lower.js ) |Medium|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments