问题描述
改变一个数字,判断一个序列的最大连续上升子序列长度
问题分析
遇到的问题!
在对对象进行假设性试验 操作时候!
不要!改变!原来的!数据结构!
实现思路
首先是判断一个序列的最大连续上升序列长度方法
public static int maxlength(int[] word) {
int len = 1;
int maxn = 1;
int[] temp1=new int[word.length];
for (int h=0;h<word.length;h++){
temp1[h]=word[h];
}
for (int q = 0; q < temp1.length - 1; q++) {
if (temp1[q] < temp1[q + 1]) {
len++;
maxn = Math.max(maxn, len);
} else {
len = 1;
}
}
return maxn;
}
然后利用该方法,对数组进行遍历,每次遍历修改一个数字,比后面一位数小,最后一位数修改为比它前一个数大,
然后对得出修改后的数组的连续上升字序列的最大长度。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int[] word = new int[num];
int max = 1;
for (int i = 0; i < num; i++)
word[i] = sc.nextInt();
for (int i = 0; i < num ; i++) {
if (i < num - 1) {
int[] temp=new int[word.length];
for (int h=0;h<word.length;h++){
temp[h]=word[h];
}
temp[i] = temp[i + 1] - 1;
max = Math.max(max, maxlength(temp));
}
if (i == (num - 1)) {
word[i] = word[i - 1] + 1;
max = Math.max(max, maxlength(word));
}
}
System.out.print(max);
}
}