# 9.Longest Increasing Subsequence

```
Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4 
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
```

## Solution I: Dynamic Programming&#x20;

**Using an array to store LIS for each index.**

```cpp
class Solution
{
public:
    int lengthOfLIS(vector<int> &nums)
    {

        int n = nums.size();

        int i = 0;
        int j = 1;
        vector<int> v(n, 1);

        while (j < n)
        {

            while (i <= j)
            {
                if (nums[i] < nums[j])
                {
                    v[j] = max(v[j], v[i] + 1);
                }

                i++;
            }

            i = 0;
            j = j + 1;
        }

        int max = 0;
        for (int k = 0; k < n; k++)
        {
            if (v[k] > max)
            {
                max = v[k];
            }
        }

        return max;
    }
};
```

**Time Complexity: O(N^2),  Space Complexity: O(n)**

## Solution II: (DP + Binary Search)

```cpp
class Solution
{
public:
    int lengthOfLIS(vector<int> &nums)
    {

        if (nums.size() == 0)
        {
            return 0;
        }

        vector<int> lis;
        lis.push_back(nums[0]);

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

            int end = lis.size() - 1;

            if (nums[i] > lis[end])
            {
                lis.push_back(nums[i]);
            }
            else
            {
                auto itr = lower_bound(lis.begin(), lis.end(), nums[i]);
                int idx = itr - lis.begin();
                lis[idx] = nums[i];
            }
        }

        return lis.size();
    }
};
```

**Time Complexity: O(n log n)**

## Lower Bound Implementation

```cpp
   int lowerBound(vector<int> &v, int target)
    {

        int start = 0;
        int end = v.size();

        while (start < end)
        {
            int mid = (start + end) / 2;
            if (target >= v[mid])
            {
                end = mid;
            }
            else
            {
                start = mid;
            }
        }
        return start;
    }
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://soumyajit4419.gitbook.io/ds-algo/dynamic-programming/6.longest-increasing-subsequence.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
