Longest Increasing Seq VS Longest Increasing Subarray
Longest increasing subarray is continuous.
E.g.
{1 2 3 3 2 4 6 7}
Longest increasing Seq is {1 2 3 4 6 7}
Longest increasing subarray is {2 4 6 7}
The first one is what we called LIS, there are O(n^2) and O(nlgn)(need to learn).
public int lengthOfLIS(int[] nums) {
if(nums.length < 2) return nums.length;
int [] dp = new int[nums.length];
int maxLen = 1;
dp[0] = 1;
for(int i = 1 ; i < nums.length; i++){
dp[i] = 1;
for(int j = i - 1; j >= 0; j--){
if(nums[i] > nums[j])
dp[i] = Math.max(dp[i], dp[j] + 1);
}
maxLen = Math.max(maxLen, dp[i]);
}
return maxLen;
}
The second one can be solve by a pointer in O(n) time complexity.
public int[] longestIncreasingSubarray(int[] nums){
if(nums.length <= 1) return nums;
int position = 0, len = 1, maxLen = 1;
for(int i = 1 ; i < nums.length; i++){
if(nums[i] > nums[i - 1]){
len ++;
}else{
if(maxLen < len){
position = i - len;
maxLen = len;
}
len = 1;
}
}
if(maxLen < len){
position = i - len;
maxLen = len;
}
int []res = new int[maxLen];
for(int i = position; i < position + maxLen; i++){
res[i - position] = nums[i];
}
return res;
}