题目描述
初始代码
import java.util.*;
public class Main {
static final int N = 1010;
static int[] arr = new int[N];
static int[] f = new int[N], g = new int[N];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
String[] s = sc.nextLine().split(" ");
for (int i = 1; i <= n; i++) arr[i] = Integer.parseInt(s[i - 1]);
int res = 0;
for (int i = 1; i <= n; i++) {
f[i] = 1;
for (int j = 1; j < i; j++)
if (arr[i] > arr[j]) f[i] = Math.max(f[i], f[j] + 1);
}
for (int i = n; i > 0; i--) {
g[i] = 1;
for (int j = n; j > i; j--)
if (arr[i] > arr[j]) g[i] = Math.max(g[i], g[j] + 1);
}
for (int i = 1; i <= n; i++) res = Math.max(res, f[i] + g[i] - 1);
System.out.println(res);
}
}
简短
import java.util.*;
public class Main {
static final int N = 1010;
static int[] arr = new int[N];
static int[] f = new int[N];
public static void main(String[] arfs) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
String[] s = sc.nextLine().split(" ");
for (int i = 1; i <= n; i++) arr[i] = Integer.parseInt(s[i - 1]);
int res = 0;
for (int i = 1; i <= n; i++) {
f[i] = 1;
for (int j = 1; j < i; j++)
if (arr[i] > arr[j]) f[i] = Math.max(f[i], f[j] + 1);
}
for (int i = n; i > 0; i--) {
int t = f[i];
f[i] = 1;
for (int j = n; j > i; j--)
if (arr[i] > arr[j]) f[i] = Math.max(f[i], f[j] + 1);
res = Math.max(res, t + f[i] - 1);
}
System.out.println(res);
}
}
算法2
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
C++ 代码
blablabla