Longest Increasing Subsequence
Completed
Read n integers and print the length of the longest strictly increasing subsequence (O(n²) DP is fine).
Input
n, then n integers.
Output
One integer.
Example
Input
8 10 9 2 5 3 7 101 18
Output
4
Editor
Java
Hints
len[i] = longest increasing subsequence ending at i.
Solution explanation
Each element extends the best subsequence that ends at a smaller earlier element.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
int[] len = new int[n];
int best = 0;
for (int i = 0; i < n; i++) {
len[i] = 1;
for (int j = 0; j < i; j++) {
if (a[j] < a[i]) len[i] = Math.max(len[i], len[j] + 1);
}
best = Math.max(best, len[i]);
}
System.out.println(best);
}
}