-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLIS.cpp
More file actions
36 lines (34 loc) · 1023 Bytes
/
Copy pathLIS.cpp
File metadata and controls
36 lines (34 loc) · 1023 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
35
36
#include <iostream>
#include <vector>
#include <cstddef>
#include <algorithm>
int longIncreaseSequence(std::vector<int>& nums, std::vector<int>* seq) {
int n = nums.size();
std::vector<int> dp(n, 1);
std::vector<int> prev(n, -1);
for (int i = 1; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (nums[j] < nums[i]) {
if (dp[i] < dp[j] + 1) {
prev[i] = j;
dp[i] = dp[j] + 1;
}
}
}
}
int index = max_element(dp.begin(), dp.end()) - dp.begin();
//i != -1, not prev i
for (int i = index; i != -1; i = prev[i]) {
seq->push_back(nums[i]);
}
reverse(seq->begin(), seq->end());
return *max_element(dp.begin(), dp.end());
}
int main () {
std::vector<int> nums = {1, 2, 7, 8, 9, 6, 7, 8, 9, 2};
std::vector<int> seq;
std::cout << longIncreaseSequence(nums, &seq) << std::endl;
for (int i = 0; i < seq.size(); ++i) {
std::cout << seq[i];
}
}