Problem:
Longest Increasing Subsequence

For a given sequence A = {a0, a1, ... , an-1}, find the length of the longest increasing subsequnece (LIS) in A.

An increasing subsequence of A is defined by a subsequence {ai0, ai1, ... , aik} where 0 ≤ i0 < i1 < ... < ik < n and ai0 < ai1 < ... < aik.

Input

n
a0
a1
:
an-1

In the first line, an integer n is given. In the next n lines, elements of A are given.

Output

The length of the longest increasing subsequence of A.

Constraints

1 ≤ n ≤ 100000

0 ≤ ai ≤ 109

Sample Input 1

5
5
1
3
2
4

Sample Output 1

3

Sample Input 2

3
1
1
1

Sample Output 2

1

Solution in JAVA (judge verdict: Time Limit Exceeded)

import java.io.*;
import java.util.*;
public class Main{
	public static void main(String args[]) throws Exception{
		Scanner cin= new Scanner(System.in);
		final int n= cin.nextInt();
		int[]   A = new int[n];
		int[][] DP= new int[n][2];
		int[]   DPi=new int[n];
		
		A[0]= cin.nextInt();
		DP[0][0]= 1;
		DP[0][1]= 0;
		DPi[0]= 1;
		int min= A[0];
		
		int i,j;
		for(i=1;i<n;i++){
			A[i]= cin.nextInt();

			if( A[i]<=min ){
				DP[i][0]= DP[i-1][0];
				DP[i][1]= DP[i-1][1];
				DPi[i]= 1;
				min= A[i];
			}
			else{
				DPi[i] =0;
				for(j=i-1;j>=0;j--){
					if( A[j]<A[i] && DPi[j]+1>DPi[i] ){
						DPi[i]= DPi[j]+1;
					}
				}
				if( DPi[i]>=DP[i-1][0] ){
					DP[i][0]= DPi[i];
					if( DPi[i]==DP[i-1][0] && A[DP[i-1][1]]<A[i] ){
						DP[i][1]= DP[i-1][1];
					}
					else{
						DP[i][1]= i;
					}
				}
				else{
					DP[i][0]= DP[i-1][0];
					DP[i][1]= DP[i-1][1];
				}
			}
		}
		
		System.out.println(DP[n-1][0]);
	}
}