Skip to content

Commit 92bfbdd

Browse files
authored
Longest Increasing Subsequence code added in C++
1 parent b7b634d commit 92bfbdd

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

LIS.cpp

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
int main()
5+
{
6+
int n, i, j, l, max_indx;
7+
vector<int> LIS;
8+
9+
cout << "Enter the length of Series: ";
10+
cin >> n;
11+
12+
int arr[n];
13+
14+
cout << "Enter values of the Series: ";
15+
for(i=0; i<n; i++)
16+
{
17+
cin >> arr[i];
18+
}
19+
cout << endl;
20+
21+
int len[n], prev[n];
22+
fill_n(len, n, 1);
23+
fill_n(prev, n, -1);
24+
25+
for(i=0; i<n; i++)
26+
{
27+
for(j=i+1; j<n; j++)
28+
{
29+
if(arr[i] < arr[j]) // for LDS change this condition to arr[i] > arr[j]
30+
{
31+
prev[j] = (len[i]+1 >= len[j]) ? i : prev[j];
32+
len[j] = max(len[j], len[i]+1);
33+
}
34+
}
35+
}
36+
37+
l = *max_element(len, len+n);
38+
max_indx = distance(len, max_element(len, len+n));
39+
40+
int v = max_indx;
41+
for(i=0; i<l; i++)
42+
{
43+
LIS.push_back(arr[v]);
44+
v = prev[v];
45+
}
46+
47+
reverse(LIS.begin(), LIS.end());
48+
49+
cout << "Length of LIS = " << l << endl;
50+
cout << "The LIS is ";
51+
for(i=0; i<LIS.size(); i++)
52+
{
53+
cout << LIS[i];
54+
55+
if(i != LIS.size()-1)
56+
cout << ", ";
57+
else
58+
cout << endl;
59+
}
60+
61+
return 0;
62+
}

0 commit comments

Comments
 (0)