Geeksforgeeks interview question-Longest Increasing Subsequence

Source: Internet
Author: User

Longest Increasing Subsequence

The longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order.

For example, length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80 }.


Note:
1. The selected values do not have to be consecutive and can be separated, but the order cannot be disordered.
2. The interval does not need to be calculated. Only the length of the selected number can be calculated.


Ideas:

1 starts from the minimum two.

2 when calculating the I value, you only need to compare the [I] value with all the values before I, as long as A [I] is larger than any other value A [j, then, the dynamic planning table v [I] is filled in with the maximum values of v [j] + 1 and v [I ].

V [j] + 1 indicates that the maximum incrementing subsequence before j values is v [j], and + 1 indicates adding the I value A [I], then the ascending subsequence is increased by 1.


Dynamic Programming is a good solution:

int longestIncreaseSubsequence(int A[], int n){vector
 
   v(n, 1);int maxL = 1;for (int i = 1; i < n; i++){for (int j = 0; j < i; j++){if (A[i] > A[j]) v[i] = max(v[i], v[j]+1);maxL = max(maxL, v[i]);}}return maxL;}int main(){    int arr[] = { 10, 22, 9, 33, 21, 50, 41, 10 };    int n = sizeof(arr)/sizeof(arr[0]);    printf("Length of LIS is %d\n",  longestIncreaseSubsequence( arr, n ));    system("pause");    return 0;}
 

The answer to the test example is 4.


Related Article

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.