Description
一个数的序列bi,当b1 < b2 < ... < bS的时候,我们称这个序列是上升的。对于给定的一个序列(a1, a2, ..., aN),我们可以得到一些上升的子序列(ai1, ai2, ..., aiK),这里1 <= i1 < i2 < ... < iK <= N。比如,对于序列(1, 7, 3, 5, 9, 4, 8),有它的一些上升子序列,如(1, 7), (3, 4, 8)等等。这些子序列中最长的长度是4,比如子序列(1, 3, 5, 8).
你的任务,就是对于给定的序列,求出最长上升子序列的长度。
Input
输入的第一行是序列的长度N (1 <= N <= 1000)。第二行给出序列中的N个整数,这些整数的取值范围都在0到10000。
Output
最长上升子序列的长度。
Sample Input
7
1 7 3 5 9 4 8
Sample Output
4
HINT
Source
代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();// 输入一维数组个数
int[] a = new int[n];// 储存数组元素
int[] sum = new int[n];// 储存每一位数字对应上升子序列长度
int i, j;
int max = 0;// 最大上升子序列长度
for (i = 0; i < n; i++) {
a[i] = s.nextInt();
}
for (i = 0; i < n; i++) {
sum[i] = 1;// 每一位数字刚开始对应上升子序列长度都设为1
for (j = 0; j < i; j++) {
if (a[i] > a[j])
sum[i] = Math.max(sum[i], sum[j] + 1);// 如果后面的数大于前面的数,他的最大上升子序列为前面数上升子序列加一
max = Math.max(max, sum[i]);
}
}
System.out.println(max);
}
}