2019-05-09 19:32:54 +08:00
|
|
|
package DynamicProgramming;
|
|
|
|
|
2017-09-29 11:47:05 +08:00
|
|
|
import java.util.Scanner;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @author Afrizal Fikri (https://github.com/icalF)
|
|
|
|
*/
|
|
|
|
public class LongestIncreasingSubsequence {
|
2019-02-06 10:13:55 +08:00
|
|
|
public static void main(String[] args) {
|
2017-09-29 11:47:05 +08:00
|
|
|
|
|
|
|
Scanner sc = new Scanner(System.in);
|
|
|
|
int n = sc.nextInt();
|
|
|
|
|
|
|
|
int ar[] = new int[n];
|
|
|
|
for (int i = 0; i < n; i++) {
|
|
|
|
ar[i] = sc.nextInt();
|
|
|
|
}
|
|
|
|
|
|
|
|
System.out.println(LIS(ar));
|
2020-01-29 00:34:52 +08:00
|
|
|
sc.close();
|
2017-09-29 11:47:05 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
private static int upperBound(int[] ar, int l, int r, int key) {
|
2019-02-06 10:13:55 +08:00
|
|
|
while (l < r - 1) {
|
2020-05-25 05:21:28 +08:00
|
|
|
int m = (l + r) >>> 1;
|
2017-09-29 11:47:05 +08:00
|
|
|
if (ar[m] >= key)
|
|
|
|
r = m;
|
|
|
|
else
|
|
|
|
l = m;
|
|
|
|
}
|
|
|
|
|
|
|
|
return r;
|
|
|
|
}
|
|
|
|
|
2017-10-04 00:26:07 +08:00
|
|
|
private static int LIS(int[] array) {
|
2017-09-29 11:47:05 +08:00
|
|
|
int N = array.length;
|
|
|
|
if (N == 0)
|
|
|
|
return 0;
|
2019-02-06 10:13:55 +08:00
|
|
|
|
2017-09-29 11:47:05 +08:00
|
|
|
int[] tail = new int[N];
|
2019-02-06 10:13:55 +08:00
|
|
|
|
|
|
|
// always points empty slot in tail
|
|
|
|
int length = 1;
|
|
|
|
|
2017-09-29 11:47:05 +08:00
|
|
|
tail[0] = array[0];
|
|
|
|
for (int i = 1; i < N; i++) {
|
|
|
|
|
|
|
|
// new smallest value
|
|
|
|
if (array[i] < tail[0])
|
|
|
|
tail[0] = array[i];
|
|
|
|
|
2019-02-06 10:13:55 +08:00
|
|
|
// array[i] extends largest subsequence
|
|
|
|
else if (array[i] > tail[length - 1])
|
2017-09-29 11:47:05 +08:00
|
|
|
tail[length++] = array[i];
|
|
|
|
|
2019-02-06 10:13:55 +08:00
|
|
|
// array[i] will become end candidate of an existing subsequence or
|
|
|
|
// Throw away larger elements in all LIS, to make room for upcoming grater elements than array[i]
|
|
|
|
// (and also, array[i] would have already appeared in one of LIS, identify the location and replace it)
|
2017-09-29 11:47:05 +08:00
|
|
|
else
|
2019-02-06 10:13:55 +08:00
|
|
|
tail[upperBound(tail, -1, length - 1, array[i])] = array[i];
|
2017-09-29 11:47:05 +08:00
|
|
|
}
|
2019-02-06 10:13:55 +08:00
|
|
|
|
2017-09-29 11:47:05 +08:00
|
|
|
return length;
|
|
|
|
}
|
|
|
|
}
|