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

You code should return the length of the LIS.

Have you met this question in a real interview?

Yes

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 elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique.

  • https://en.wikipedia.org/wiki/Longest_increasing_subsequence

Example

For[5, 4, 1, 2, 3], the LIS is[1, 2, 3], return3
For[4, 2, 4, 5, 3, 7], the LIS is[2, 4, 5, 7], return4

Challenge

Time complexity O(n^2) or O(nlogn)

class Solution {

public:

/\*\*

 \* @param nums: The integer array

 \* @return: The length of LIS \(longest increasing subsequence\)

 \*/

int longestIncreasingSubsequence\(vector<int> nums\) {

    // write your code here

    vector<int> tail;

    for \(int i = 0; i < nums.size\(\); ++i\) {

        auto it = lower\_bound\(tail.begin\(\), tail.end\(\), nums\[i\]\);

        if \(it != tail.end\(\)\) {

            \*it = nums\[i\];

        } else {

            tail.push\_back\(nums\[i\]\);

        }

    }



    return tail.size\(\);

}

};

class Solution {

public:

/\*\*

 \* @param nums: The integer array

 \* @return: The length of LIS \(longest increasing subsequence\)

 \*/

int longestIncreasingSubsequence\(vector<int> nums\) {

    // write your code here

    if \(nums.empty\(\)\) {

        return 0;

    }

    int n = nums.size\(\);

    int best = 1;

    vector<int> f\(n, 1\);

    for \(int i = 1; i < n; ++i\) {

        for \(int j = 0; j < i; ++j\) {

            if \(nums\[j\] >= nums\[i\]\) {

                continue;

            }

            f\[i\] = max\(f\[i\], f\[j\] + 1\);

        }

        best = max\(best, f\[i\]\);

    }

    return best;

}

};

results matching ""

    No results matching ""