-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLIS
More file actions
39 lines (30 loc) · 1.07 KB
/
Copy pathLIS
File metadata and controls
39 lines (30 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package lis; //最长上升子序列
import java.util.Scanner;
public class Main {
/**
* 给你一个长度为n的序列,a[1],a[2],a[3]......a[n],求其最长上升子序列长度。
最长上升子序列:递增的可间断的子序列,比如序列 1,3,-3,5,-2,6,其最长上升子序列为1,3,5,6. 最大上升子序列的长度为4.
* @param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt(); //该序列中数据的个数
int[] arr = new int[n];
int[] dp = new int[n]; //dp[i]为当前序列的长度
for (int i = 0; i < n; i++) {
arr[i] = input.nextInt(); //录入数据
dp[i] = 1;
}
int ans = 0;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (arr[j] < arr[i]) {
dp[i] = Math.max(dp[j] + 1, dp[i]); //通项公式 若dp[j]的长度加上arr[j]这个数的长度 > dp[i],则dp[i] = dp[j] + 1
}
}
ans = Math.max(ans, dp[i]); //ans为最大子序列长度
}
System.out.println(ans);
input.close();
}
}