712383. Number of Longest Increasing Subsequence
Medium
Here is the detailed Markdown blog post for the problem:
Number of Longest Increasing Subsequence
Summary
Given an array of integers, find the number of longest increasing subsequences (LIS) in the array. A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
The key concept involved is dynamic programming.
Detailed Explanation
To solve this problem, we will use dynamic programming to find the number of longest increasing subsequences (LIS) in the array. The idea is to create a 2D array dp where dp[i][j] represents whether there exists an increasing subsequence with length j ending at index i.
Here's the step-by-step breakdown:
- Initialize a 2D array
dpof size(n x (max + 1)), wherenis the length of the input array andmaxis the maximum value in the array. - Iterate through the array from left to right:
- For each element at index
i, iterate fromj = 1tomax:- Check if there exists an increasing subsequence with length
j-1ending at indexi-1. If yes, and the current element is greater than or equal to the last element of that subsequence, then updatedp[i][j]todp[i-1][j-1] + 1. - If no such subsequence exists, set
dp[i][j] = 0.
- Check if there exists an increasing subsequence with length
- For each element at index
- The value at
dp[n-1][max]represents the number of longest increasing subsequences (LIS) in the array.
Time complexity: O(n * max) Space complexity: O(n * max)
Optimized Solutions
Java
public int findNumberLongestIncreasingSubsequence(int[] arr) {
int n = arr.length;
int max = Arrays.stream(arr).max().getAsInt();
int[][] dp = new int[n][max + 1];
for (int i = 0; i < n; i++) {
for (int j = 1; j <= max; j++) {
if (i == 0 || arr[i] >= arr[i-1]) {
dp[i][j] = (dp[i-1][j-1] > 0) ? dp[i-1][j-1] + 1 : 0;
} else {
dp[i][j] = 0;
}
}
}
return dp[n-1][max];
}