← Home

368. Largest Divisible Subset

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
dynamic programmingC++Markdown
368

The trick here is to name the state correctly, then let the implementation follow. For 368. Largest Divisible Subset, the solution in this repository is mainly a dynamic programming solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: dynamic programming, backtracking.

The notes already sitting in the source point us in the right direction:

  • WA
  • 35 / 41 test cases passed.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are largestDivisibleSubset, length, pre.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N^2), space: O(N)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//WA
02//35 / 41 test cases passed.
03class Solution {
04public:
05    vector<int> largestDivisibleSubset(vector<int>& nums) {
06        int n = nums.size();
07        if(n == 0) return nums;
08        vector<vector<int>> subsets;
09        sort(nums.begin(), nums.end());
10        for(int i = 0; i < n; i++){
11            for(vector<int>& subset : subsets){
12                if(nums[i] % subset.back() == 0){
13                    subset.push_back(nums[i]);
14                }
15            }
16            subsets.push_back({nums[i]});
17        }
18        
19        // for(vector<int>& subset : subsets){
20        //     for(int e : subset){
21        //         cout << e << " ";
22        //     }
23        //     cout << endl;
24        // }
25        
26        sort(subsets.begin(), subsets.end(),
27            [](const vector<int>& a, const vector<int>& b){
28                return (a.size() == b.size()) ? a[0] < b[0] : a.size() > b.size();
29            });
30        
31        return subsets[0];
32    }
33};
34
35//LIS
36//https://leetcode.com/problems/largest-divisible-subset/discuss/84006/Classic-DP-solution-similar-to-LIS-O(n2)
37//Runtime: 36 ms, faster than 94.57% of C++ online submissions for Largest Divisible Subset.
38//Memory Usage: 8.5 MB, less than 67.33% of C++ online submissions for Largest Divisible Subset.
39//time: O(N^2), space: O(N)
40class Solution {
41public:
42    vector<int> largestDivisibleSubset(vector<int>& nums) {
43        int n = nums.size();
44        if(n == 0) return nums;
45        vector<int> length(n, 1); //length of subset
46        vector<int> pre(n, -1); //the index of the previous element in the same subset
47        
48        //this is important!
49        sort(nums.begin(), nums.end());
50        //record the largest subset and its last element's index
51        int maxLength = 0, maxIndex = -1;
52        for(int i = 0; i < n; i++){
53            for(int j = 0; j < i; j++){
54            // for(int j = i-1; j >= 0; j--){
55                if(nums[i] % nums[j] == 0){
56                    //can choose to append nums[i] after nums[j]'s subset
57                    if(length[j] + 1 > length[i]){
58                        /*
59                        append nums[i] after nums[j]'s subset: 
60                        get subset of length[j] + 1
61                        not append nums[i] after nums[j]'s subst:
62                        i's subset's length remains length[i]
63                        */
64                        length[i] = length[j] + 1;
65                        pre[i] = j;
66                    }
67                }
68            }
69            if(length[i] > maxLength){
70                maxLength = length[i];
71                maxIndex = i;
72            }
73        }
74        
75        //backtracking to get the max subset
76        cout << length[maxIndex] << ", " << maxLength << endl;
77        vector<int> ans(length[maxIndex]);
78        int index = maxIndex;
79        
80        for(int i = ans.size()-1; i >= 0; i--){
81            ans[i] = nums[index];
82            index = pre[index];
83        }
84        
85        return ans;
86    }
87};

Cost

Complexity

Time
O(N^2), space: O(N)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.