最长递增子序列dp
Problem: You are given an array of length N. You have to find the longest increasing subsequence.
问题:给您一个长度为N的数组。 您必须找到最长的递增子序列 。
Constraints: 1 <= N <= 10^4
限制条件: 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.
我们必须找到最长的递增子序列的长度。 在样本输入中, 最长的递增子序列为1,3,8,67,因此其长度为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.
在转到代码之前,我们可以看到递归解决方案将显示超出时间限制。 由于递归解的时间复杂度为O(2 ^(N)) 。 因此,我们绝对必须使用DP。 我将使用一维数组,其中第 i 个单元格代表最长递增子序列的长度,直到原始数组中的第 i 个索引。
So now is the code of above approach:
现在是上述方法的代码:
#include <iostream>
using namespace std;
int LIS(int arr[], int n){
int dp[n] = {0};
dp[0] = 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.
虽然我使用线性数组存储数组,但时间复杂度为O(N ^ 2) 。 在动态编程方法中,矩阵的维数不必是程序的时间复杂度。
最长递增子序列dp