Lintcode-medium-longest increasing subsequence

Source: Internet
Author: User

Given a sequence of integers, find the longest increasing subsequence (LIS).

You code should return the length of the LIS.

Clarification

What ' s the definition of longest increasing subsequence?

* The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence ' s Eleme NTS is in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence are not necessarily contiguous, or unique.

* Https://en.wikipedia.org/wiki/Longest_common_subsequence_problem

Example

For [5, 4, 1, 2, 3], the LIS is [1, 2, 3], return 3

For [4, 2, 4, 5, 3, 7], the LIS is [4, 4, 5, 7], return 4

Dynamic planning:

Use an int array to represent the number of I as the last subsequence length

So as long as the back number is larger than the previous number, the oldest sequence length is updated.

Finally, traversing one side of the DP array, select the maximum value

 Public classSolution {/**     * @paramnums:the Integer Array *@return: The length of LIS (longest increasing subsequence)*/     Public intLongestincreasingsubsequence (int[] nums) {        //Write your code here                if(Nums = =NULL|| Nums.length = = 0)            return0; int[] DP =New int[Nums.length]; intLongest = 1;  for(inti = 0; i < nums.length; i++) Dp[i]= 1;  for(inti = 0; i < dp.length; i++){             for(intj = i + 1; J < Dp.length; J + +){                if(Nums[j] >=Nums[i]) {Dp[j]= Math.max (Dp[j], dp[i] + 1); }            }        }                 for(inti = 0; i < dp.length; i++) Longest=Math.max (Longest, dp[i]); returnlongest; }}

Lintcode-medium-longest increasing subsequence

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.