# Longest increasing sequences

*Given an unsorted array of integers, find the length of longest increasing subsequence.

For example, Given [10, 9, 2, 5, 3, 7, 101, 18], The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that 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?

https://leetcode.com/problems/longest-increasing-subsequence/*

Solution:

1. Dynamic programming O(N^2) Complexity

``````state function: res[j] means the longest increasing sequence end with nums[j]

res[i] = max(res[j], 1) 0 <= j <= i

public int lengthOfLIS(int[] nums) {
if (nums.length == 0) {
return 0;
}
int[] res = new int[nums.length];
res = 1;
int max = 1;
for (int i = 1; i < nums.length; i++) {
res[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j] && res[i] < res[j] + 1) {
res[i] = res[j]+1;
}
max = Math.max(res[i], max);
}
}
return max;
}
``````

2. Binary search O(NlgN) complexity

``````Detailed explanations:
http://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/

Reference: without extra memory

public int lengthOfLIS(int[] nums) {
int N = 0, idx, x;
for(int i = 0; i < nums.length; i++) {
x = nums[i];
if (N < 1 || x > nums[N-1]) {
nums[N++] = x;
} else if ((idx = Arrays.binarySearch(nums, 0, N, x)) < 0) {
nums[-(idx + 1)] = x;
}
}
return N;
}
``````

Optimized solution:

``````public class Solution {
public int lengthOfLIS(int[] nums) {
int len = 0, n = nums.length;
for (int i: nums) {
int j = BinarySearch(nums, 0, len-1, i);
nums[j] = i;
if (j == len) len++;
}
return len;
}

public int BinarySearch(int[] a, int l, int r, int key) { // find target position or insertion position
while (l <= r) {
int m = l+(r-l)/2;
if (a[m] >= key)
r = m-1;
else l = m+1;
}
return l;
}
}
``````

Extended study: patience sorting