Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Note:
There may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
TS - N square
SC - N
Pseudo Code:-
1. Define LIS array as same length of input array and initialize it with 1 because each number makes at least LIS of length 1.
2. Run outer loop 0 to n-1 with index i
3. Run inner loop 0 to i-1
4 check if (nums[i] > nums[j]) then
LIS[i] = Math.max(LIS[i], 1 + LIS[j]);
Code:-
class Solution {
public int lengthOfLIS(int[] nums) {
int n = nums.length;
int[] LIS=new int[n];
for (int i = 0; i < n; i++) {
LIS[i] = 1;
} for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j])
LIS[i] = Math.max(LIS[i], 1 + LIS[j]);
}
} int ans = 0;
for (int i = 0; i < n; i++) {
ans = Math.max(ans, LIS[i]);
}
return ans;
}}