-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest_increasing_subsequence.cpp
94 lines (73 loc) · 1.84 KB
/
longest_increasing_subsequence.cpp
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <bits/stdc++.h>
using namespace std;
int longest_increasing_subsequence_recursive(int *arr, int n, int pos, int *overall_longest) {
int longest = 0;
int candidate;
for (int i = pos - 1; i >= 0; i--) {
candidate = longest_increasing_subsequence_recursive(arr, n, i, overall_longest);
if (arr[i] < arr[pos]) {
longest = max(longest, candidate);
}
}
*overall_longest = max(*overall_longest, longest + 1);
return longest + 1;
}
int longest_increasing_subsequence_topdown(int *arr, int n, int pos, int *dp) {
if (dp[pos]) {
return dp[pos];
}
int longest = 0;
int candidate;
for (int i = pos - 1; i >= 0; i--) {
candidate = longest_increasing_subsequence_topdown(arr, n, i, dp);
if (arr[i] < arr[pos]) {
longest = max(longest, candidate);
}
}
return dp[pos] = longest + 1;
}
int longest_increasing_subsequence_bottomup(int *arr, int n, int *dp) {
int longest_previous_subsequence;
int longest_subsequence = 0;
dp[0] = 1;
for (int i = 1; i < n; i++) {
longest_previous_subsequence = 0;
for (int j = i - 1; j >= 0; j--) {
if (arr[j] < arr[i]) {
longest_previous_subsequence = max(longest_previous_subsequence, dp[j]);
}
}
dp[i] = 1 + longest_previous_subsequence;
longest_subsequence = max(longest_subsequence, dp[i]);
}
return longest_subsequence;
}
void solve() {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int recursive_overall_longest = 0;
int dp[n] = {0};
cout << longest_increasing_subsequence_bottomup(arr, n, dp);
//cout << recursive_overall_longest;
// int longest = 0;
// for (int i = 0; i < n; i++) {
// longest = max(longest, dp[i]);
// }
// cout << longest;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}