Longest Increasing Subsequence using Dynamic programming (DP)

Here, we are going to learn how to find the longest increasing subsequence using dynamic programming (DP)?
Submitted by Ritik Aggarwal, on November 13, 2018

Problem: You are given an array of length N. You have to find the longest increasing subsequence.

Constraints: 1 <= N <= 10^4

```    Sample inputs:
6
10 1 3 8 81 67

Sample output:
4
```

Explanation of the problem:

We have to find the length of longest increasing subsequence. In sample input the longest increasing subsequence is 1,3,8,67 so length of this is 4.

Solution:

Before going to the code we can see that recursive solution will show time limit exceeded. As recursive solution has time complexity as O(2^(N)). So we definitely have to use DP. I will be using a 1D- array in which ith cell represents the length of longest increasing subsequence up to ith index in the original array.

So now is the code of above approach:

```#include <iostream>
using namespace std;

int LIS(int arr[], int n){
int dp[n] = {0};
dp = 1;
for (int col = 1; col < n; col++) {
int max = 0;
for (int i = 0; i < col; i++) {
if (arr[i] < arr[col]) {
if (max < dp[i]) {
max = dp[i];
}
}
}
dp[col] = max+1;
}
int max1 = -1000000;
for(int value : dp) {
if(max1<value) {
max1 = value;
}
}
return max1;
}

int main() {
int n;
cin >> n;
int arr[n];
for(int i = 0;i<n;i++){
cin >> arr[i];
}
cout << LIS(arr, n) << endl;
return 0;
}
```

Output

```6
10 1 3 8 81 67
4
```

Though I am using a linear array to store the arrays time complexity is O(N^2). It is not necessary that the dimension of the matrix is the time complexity of the program in the dynamic programming approach.

TOP Interview Coding Problems/Challenges

Learn PCB Designing: PCB DESIGNING TUTORIAL

 Recommended posts C Tips & Tricks, C++ Tips & Tricks Introduction to Linux (Its modes, Safety, Most popular Applications) Linux Best Distros of 2018 C programming optimization techniques Differences b/w C & Embedded C? Embedded C Interview Q. & A. C programming tips for Embedded Development Basic rules of writing a C program Important points (rules) to remember while writing C/C++ program Top 5 Websites for solving programming challenges Read more...

 Others... Computer G.K. (MCQ) Most viewed pages... Categories...

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates