【Java】最大连续递增子列数据结构算法,简明算法

该博客介绍了一种使用Java实现寻找最大连续递增子序列的算法,不依赖额外的数据结构,只需原序列和几个辅助变量。在遍历过程中动态更新最大递增子序列的起始位置和长度。最后,输出最大子序列及其长度。适用于数组或线性表操作,可轻松转换为C或Python等语言。
摘要由CSDN通过智能技术生成

最大连续递增子列【Java】数据结构算法,简明算法

用java实现,但c和python.其他语言都是一个道理

不用定义新的表,只需要原序列(表),再定义三个新的变量用于保存数据直接上代码,详细注释代码里有

如果不需要输出最大子序列只需要输出最大子序列的长度,把最后的输出删除即可

例如:
输入:15
1 9 2 5 7 3 4 6 8 0 11 15 17 17 10
输出:3 4 6 8

public class MaximalIncreasingSubsequence {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        //        初试化线性表---
        System.out.print("线性表的长度");
        int length = scanner.nextInt();
        ArrayList<Integer> arrayList = new ArrayList<Integer>(length);
        for (int i = 0; i <length; i++) {
        	System.out.print("第"+ (i+1) +"个元素:");
            arrayList.add(scanner.nextInt());
        }

//        最大递增数组的起始位置和递增位数
        int MaxPosition = 0;
        int MaxLength = 0;

//        计算当前数组的长度
        int CurrentLength = 0;

        for (int i = 0; i < arrayList.size()-1; i++) {
            if (arrayList.get(i) < arrayList.get(i+1)){
                CurrentLength++;
            }
            else {
//                将当前递增数组长度重置
                CurrentLength = 0;
            }

//            判断当前递增数组是否为最大递增数组
            if (CurrentLength > MaxLength){
//                将当前递增数组的开始位置赋给MaxPosition [注]要加上1才能保证位置相同
                MaxPosition = i - CurrentLength + 1;
//                将最大数组长度赋给MaxLength
                MaxLength = CurrentLength;
            }
        }
//		  输出最大子序列的开始位置和长度
        System.out.print("最大数组开始位置:" + MaxPosition);
        System.out.println("  "+"最大数组长度:" + MaxLength+1);
//        输出最大数组
        for (int i = 0; i <=  MaxLength; i++) {
            System.out.println(arrayList.get(MaxPosition));
            MaxPosition++;
        }


    }
}

如果有什么bug请指正==。==

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值