forked from Nimesh-Srivastava/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0368.cpp
More file actions
34 lines (25 loc) · 874 Bytes
/
0368.cpp
File metadata and controls
34 lines (25 loc) · 874 Bytes
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
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
//works on both C++ and C style arrays
sort(begin(nums), end(nums));
int siz = size(nums);
int maxVal = 0;
vector<int> dp(siz, 1);
vector<int> prev(siz, -1);
for(int i = 1; i < siz; i++){
for(int j = 0; j < i; j++){
if(nums[i] % nums[j] == 0 && dp[i] < dp[j] + 1){
dp[i] = dp[j] + 1;
prev[i] = j;
}
if(dp[i] > dp[maxVal])
maxVal = i;
}
}
vector<int> result;
for(int cnt = maxVal; cnt >= 0; cnt = prev[cnt])
result.push_back(nums[cnt]);
return result;
}
};