TheAlgorithms-C-Plus-Plus/dynamic_programming/Longest Increasing Subsequence.cpp

39 lines
671 B
C++
Raw Normal View History

2016-11-26 11:46:32 +08:00
//Program to calculate length of longest increasing subsequence in an array
#include <bits/stdc++.h>
using namespace std;
2019-08-21 10:10:08 +08:00
int LIS(int a[], int n)
{
2016-11-26 11:46:32 +08:00
int lis[n];
for (int i = 0; i < n; ++i)
{
lis[i] = 1;
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < i; ++j)
{
2019-08-21 10:10:08 +08:00
if (a[i] > a[j] && lis[i] < lis[j] + 1)
2016-11-26 11:46:32 +08:00
lis[i] = lis[j] + 1;
}
}
int res = 0;
for (int i = 0; i < n; ++i)
{
2019-08-21 10:10:08 +08:00
res = max(res, lis[i]);
2016-11-26 11:46:32 +08:00
}
return res;
}
int main(int argc, char const *argv[])
{
int n;
2019-08-21 10:10:08 +08:00
cout << "Enter size of array: ";
cin >> n;
2016-11-26 11:46:32 +08:00
int a[n];
2019-08-21 10:10:08 +08:00
cout << "Enter array elements: ";
2016-11-26 11:46:32 +08:00
for (int i = 0; i < n; ++i)
{
2019-08-21 10:10:08 +08:00
cin >> a[i];
2016-11-26 11:46:32 +08:00
}
2019-08-21 10:10:08 +08:00
cout << LIS(a, n) << endl;
2016-11-26 11:46:32 +08:00
return 0;
}