Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18] ,
The longest increasing subsequence [2, 3, 7, 101] is and therefore the length is 4 . Note that there could be more than one LIS combination, it's only necessary for you and return the length.
Your algorithm should run in O (n2) complexity.
Follow up:could you improve it to O (n log n) time complexity?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.
1 Public classSolution {2 Public intLengthoflis (int[] nums) {3 if(Nums = =NULL|| Nums.length = = 0)return0;4 int[] DP =New int[nums.length];5 intMax = 0;6Arrays.fill (dp,1);7 for(inti = 0; i<nums.length; i++){8 for(intj = 0; J <= i;j++){9 if(Nums[i] > Nums[j] && dp[j] + 1 >Dp[i])TenDp[i] = Dp[j] + 1; One } AMax =Math.max (Max,dp[i]); - } - returnMax; the } -}
Traverse the entire sequence sequentially, each time finding the longest ascending subsequence from the first number to the current number, until the last number is traversed, and then the largest ascending subsequence of the entire sequence is taken from the DP array.
We use Dp[i] to store the length of the longest ascending subsequence of the sequence 1-i, then Dp[i]=max (Dp[j]) +1, (J∈[1, i-1]); Obviously Dp[1]=1, we start by traversing the elements behind the i=2.
The basic solution of the Problem O (n*n), the optimization of the Solution O (NLOGN) Two brush time and then the solution.
Longest increasing subsequence Java solutions