712574. Print Longest Increasing Subsequence
Printing Longest Increasing Subsequence
Summary
Print the longest increasing subsequence (LIS) from a given array. The LIS is a sequence that contains no two elements which are adjacent to each other and are in order.
The problem involves dynamic programming, as we need to keep track of the length of the longest increasing subsequence seen so far at every step.
Detailed Explanation
To solve this problem, we can use dynamic programming. We initialize an array dp where dp[i] is the length of the LIS ending at index i. Then, for each element in the array, we update dp[i] to be the maximum of its current value and 1 + dp[j], where j < i and arr[j] < arr[i].
Here's a step-by-step breakdown:
- Initialize an array
dpof sizen+1, wherenis the length of the input array. - Iterate over the input array, and for each element at index
i, find the maximumjsuch thatarr[j] < arr[i]. - Update
dp[i]to be the maximum of its current value (1) and1 + dp[j]. - Return the maximum value in
dp.
Here's a diagram illustrating this process:
0, 1, 2, 3, 4
arr = [5, 2, 7, 1, 6]
0, 1, 2, 3, 4
dp = [1, 1, 2, 2, 3]
In this example, the LIS is [2, 7], which has a length of 2. The maximum value in dp is 3, which corresponds to the length of the LIS.
Time complexity: O(n^2) Space complexity: O(n)
Optimized Solutions
Here are optimized solutions in Java, Python, C++, and JavaScript:
Java
public class Main {
public static void printLIS(int[] arr) {
int n = arr.length;
int[] dp = new int[n+1];
int maxLen = 0;
for (int i = 0; i < n; i++) {
int j = i - 1;
while (j >= 0 && arr[j] >= arr[i]) {
j--;
}
if (j == -1) {
dp[i+1] = 1;
} else {
dp[i+1] = dp[j+1] + 1;
}
maxLen = Math.max(maxLen, dp[i+1]);
}
System.out.println("Longest Increasing Subsequence of length " + maxLen);
}
public static void main(String[] args) {
int[] arr = {5, 2, 7, 1, 6};
printLIS(arr);
}
}