面试题——最长上升子串

AcWing 1490 最长上升子串

题目

​ 给出一个长度为n的由正整数构成的序列,你需要从中删除一个正整数,很显然你有很多种删除方式,你需要对删除这个正整数以后的序列求其最长上升子串,请问在所有删除方案中,最长的上升子串长度是多少。

​ 这里给出最长上升子串的定义:即对于序列中连续的若干个正整数,满足ai+1 > ai,则称这连续的若干个整数构成的子串为上升子串,在所有的上升子串中,长度最长的称为最长上升子串。

输入格式

输入第一行仅包含一个正整数n,表示给出的序列的长度。

接下来一行有n个正整数,即这个序列,中间用空格隔开。

输出格式

输出仅包含一个正整数,即删除一个数字之后的最长上升子串长度。

数据范围

1 ≤ n ≤ 100000
1 ≤ ai ≤ 100000

输入样例:

1
2
5
2 1 3 2 5

输出样例:

1
3

思路

​ 这道题我们采用枚举的做法进行求解,对于序列中任意位置 i 的数字,我们都求出它之前按顺序递增最远可以到达的距离f[i],和它之后按顺序递增最远可以到达的距离g[i],当我们要拿掉一个数字来得到最长上升子串时,我们只需要先判断拿掉了i后第i个元素两边是否可以拼接上,如果可以,拿掉i的连续上升子串的长度即为f[i - 1] + g[i + 1],不能拼接的话即为max(f[i - 1], g[i + 1]),最后取所有情况的最大值,即为最长上升子串的长度

代码

c++

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
#include <iostream>

using namespace std;

const int N = 100010;

int nums[N], f[N], g[N];
int n;
int res = 0;

int main() {

scanf("%d", &n);
for (int i = 1; i <= n; ++i) scanf("%d", &nums[i]);

for (int i = 1; i <= n; ++i)
if (nums[i] > nums[i - 1]) f[i] = f[i - 1] + 1;
else f[i] = 1;
for (int i = n; i > 0; --i)
if (nums[i] < nums[i + 1]) g[i] = g[i + 1] + 1;
else g[i] = 1;

for (int i = 1; i <= n; ++i) {
if (nums[i - 1] < nums[i + 1]) {
int a = f[i - 1] + g[i + 1];
res = a > res ? a : res;
}
else {
int a = f[i - 1] > g[i + 1] ? f[i - 1] : g[i + 1];
res = a > res ? a : res;
}
}

printf("%d", res);

}

java

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
package AcWingCode;

import java.util.Scanner;

public class p1490 {
static final int N = 100010;
public static void main(String[] args) {
int n, res = 0;
int nums[] = new int[N];
int f[] = new int[N];
int g[] = new int[N];
Scanner myInput = new Scanner(System.in);
n = myInput.nextInt();
for (int i = 1; i <= n; ++i)
nums[i] = myInput.nextInt();
for (int i = 1; i <= n; ++i) {
if (nums[i] < nums[i - 1]) f[i] = f[i - 1] + 1;
else f[i] = 1;
}
for (int i = n; i >= 1; --i) {
if (nums[i] > nums[i + 1]) g[i] = g[i + 1] + 1;
else g[i] = 1;
}
for (int i = 1; i <= n; ++i) {
if (nums[i - 1] < nums[i + 1]) {
int add = f[i - 1] + g[i + 1];
res = res > add ? res : add;
}
else {
int max = f[i - 1] > g[i + 1] ? f[i - 1] : g[i + 1];
res = res > max ? res : max;
}
}
System.out.println(res);
}
}
-------------本文结束感谢您的阅读-------------