# Longest Increasing Subsequence

#1

Given an unsorted array of integers, find the length of 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`. ```

Note:

• There may be more than one LIS combination, it is only necessary for you to return the length.
• Your algorithm should run in O(n2) complexity.

Follow up: Could you improve it to O(n log n) time complexity?

#2

The below code uses `Patience Sorting` which is a way to organize given numbers into different piles of elements where the top of the pile elements across the piles form the longest increasing subsquence.

``````class Solution {
public int lengthOfLIS(int[] nums) {
int[] piles = new int[nums.length];
int len = 0;
for(int num : nums){
int i=0, j=len;
while(i!=j){
int mid = (i+j)/2;
if(num > piles[mid]){
i = mid+1;
} else{
j=mid;
}
}
piles[i] = num;
if(i==len) len++;
}

return len;
}
}
``````

#3

The below code uses dynamic programming to find out the sequence length at every index.

``````/*
3, 4, -1, 0, 6, 2, 3
1 .2 . 1  2 .3 .3 .4

we check nums from 0 to i at every i and incremenet value if nums[j] < nums[i]

*/
class Solution {
public int lengthOfLIS(int[] nums) {
if(nums==null || nums.length==0) return 0;
int n = nums.length;
int[] dp = new int[n];
int max = 1;
Arrays.fill(dp, 1);
for(int i=1;i<n;i++){
for(int j=0;j<i;j++){
if(nums[j] < nums[i]){
dp[i] = Math.max(dp[i], dp[j]+1);
max = Math.max(max, dp[i]);
}
}
}

return max;
}
}
``````