 New update is available. Click here to update.

# Longest Increasing Subsequence

Last Updated: 24 Jul, 2020
Difficulty: Moderate

## PROBLEM STATEMENT

#### Strictly Increasing Sequence is when each term in the sequence is larger than the preceding term.

##### For example:
``````[1, 2, 3, 4] is a strictly increasing array, while [2, 1, 4, 3] is not.
``````
##### Input format:
``````The first line of input contains an integer 'N', representing the size of the array.

The second line of input contains 'N' space-separated integers, representing the elements of the array.
``````
##### Output Format:
``````The only output line contains one integer representing the length of the longest increasing subsequence.
``````
##### Note:
``````You do not need to print anything; it has already been taken care of. Just implement the given functions.
``````
##### Input Constraints
``````1 <= N <= 10^5
-10^5 <= element <= 10^5

Time Limit: 1sec
`````` ## Approach 1

• We will write a recursive algorithm that will try all the possibilities.
• The argument of recursive function will be the current index and what was the previous number used for LIS. Initially, we will be passing the previous number as the minimum number of an integer and starting index as 0.
• The base case would be when we reach index n,i.e we have exhausted the array elements so return 0 because there is no more element to contribute anything.
• Inside each function call, we consider two cases: The current element is larger than the previous element included in the LIS. In this case, we can include the current element in the LIS. Thus, we find out the length of the LIS obtained by including it.
• Further, we also find out the length of LIS possible by not including the current element in the LIS. The value returned by the current function call is, thus, the maximum out of the two lengths.
• So here is our recurrence relation:
``````if (arr[curPosition] > prev)
{
taken = 1 + lisHelper(arr[curPosition], curPosition + 1);
}

int notTaken = lisHelper(prev,curPosition + 1);
//we can always skip the current element``````
• Finally, the answer will be max(taken, notTaken)