Solution for leetcode 300
https://leetcode.com/problems/longest-increasing-subsequence/
dp[i] represents the longest subsequence ending at position [i] so that nums[i] is included
The transition matrix is : for all j < i and nums[j] < nums[i], dp[i] can be updated as the maximum value between dp[i] (original value) and dp[j] + 1
notice that for code simplicity, in our code, dp[j] is 1 smaller than the actual value (we omit the step of initializing arr elements to 1 and choose to add 1 in the end instead)
class Solution {
public int lengthOfLIS(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
int output = 0;
for(int i = 1; i < n; i++){
for(int j = 0; j < i; j++){
if(nums[j] < nums[i]){
dp[i] = Math.max(dp[i], dp[j] + 1);
output = Math.max(output, dp[i]);
}
}
}
return output + 1;
}
}
Solution for leetcode 673
https://leetcode.com/problems/number-of-longest-increasing-subsequence/
class Solution {
public int findNumberOfLIS(int[] nums) {
int n = nums.length;
//records the length of the lis upto index i
int[] dp = new int[n];
//records the number of the lis upto index i
int[] count = new int[n];
int longestLength = 1;
Arrays.fill(dp,1);
//Don't forget this step
Arrays.fill(count, 1);
for(int i = 1; i < n; i++){
for(int j = 0; j < i; j++){
if(nums[i] > nums[j]){
if(dp[j] + 1 == dp[i]){
count[i] += count[j];
}
//cover what we have before because we find a longer length now
else if(dp[j] + 1 > dp[i]){
dp[i] = dp[j] + 1;
count[i] = count[j];
longestLength = Math.max(longestLength, dp[i]);
}
}
}
}
//the lis can end at different positions
int output = 0;
for(int k = 0; k < n; k++){
if(dp[k] == longestLength){
output += count[k];
}
}
return output;
}
}