Longest increasing subsequence Java solutions

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.