求最长连续递增子序列长度

本文介绍了一种O(n)的算法,用于寻找数组中最长的连续递增子序列,并提供了一个扩展应用案例,即从数字字符串中找到最长且数值最大的连续递增子序列。

注意这个递增子序列是连续的,所以可以用O(n)的算法来实现。


保存一个全局的最大值,然后在扫描数组过程中更新。


public class LIS {
	//index is the beginning index of longest contiguous increasing sequence
	public static int index;
	//to calculate the longest contiguous increasing sequence
	public static int length(int[] A,int size){
		if(size<=0)return 0;
		int res=1;
		int current=1;
		for(int i=1;i<size;i++){
			if(A[i]>A[i-1]){
				current++;
			}
			else{
				if(current>res){
					index=i-current;
					res=current;
				}
				current=1;
			}
		}
		return res;
		
	}
	public static void main(String[] args){
		int []A={2,13,6,8,9,1};
		System.out.println(length(A,6));
		System.out.println(LIS.index);
		
	}

}


问题2:从输入的数字字符串中找最长连续递增子序列的长度,若有多个长度相同的最长递增子序列,取大小最大的那个。

比如有个递增子序列是5678,另一个递增子序列是5679,比较这两个数的大小即可

分析:把该字符串的每个元素提取到一个整数数组中,接下来的解决方案便同上个问题相同。

public class Test2 {
	public static int index;
	public static int max=0;
	public static int longestlen(int[] A,int size){
		if(size<=0)return 0;
		max=A[0];
		int res=1;
		String str="";
		int current=1;
		for(int i=1;i<size;i++){
			if(A[i]>A[i-1]){
				current++;
			}
			else{
				//A[i]<=A[i-1]
				//the last index in increasing sequence is i-1
				if(current>res){
					index=i-current;
					res=current;
					for(int j=0;j<current;j++){
						str+=Integer.toString(A[i-current+j]);
					}
					max=Integer.parseInt(str);
					
				}
				else if(current==res){
					for(int j=0;j<current;j++){
						str+=Integer.toString(A[i-current+j]);
					}
					int l_max=Integer.parseInt(str);
					if(l_max>max){
						max=l_max;
						index=i-current;
					}
						
					
					
				}
				current=1;
				str="";
			}
		}
		return res;
	}
	public static int LIS(String str){
		if(str==null)return 0;
		int [] A=new int[str.length()];
		for(int i=0;i<str.length();i++)
			//A[i]=Integer.parseInt(str.charAt(i)+"");
			A[i]=Integer.parseInt(str.substring(i, i+1));
		return longestlen(A,str.length());
		
				
	}
	
	public static void main(String[] args){
		System.out.println(LIS(new String("345673578925678")));
		System.out.println(index);
		System.out.println(max);
		
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值