计蒜客——求数组最长递减子序列

给定一个整数序列,输出它的最长递减(注意不是“不递增”)子序列。

输入包括两行,第一行包括一个正整数N(N<=1000),表示输入的整数序列的长度。第二行包括用空格分隔开的N个整数,整数范围区间为[-30000,30000]。

输出为一行,最长递减子序列的结果,数字间用空格分隔(测试case中只会有一个最长递减子序列)。

样例输入

8
9 4 3 2 5 4 3 2

样例输出

9 5 4 3 2
import java.util.Scanner;

/**
 * 单调减子序列
 * @author yurong
 *
 */
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner console = new Scanner(System.in);
		int n = console.nextInt();
		int[] a = new int[n];
		int[] dp = new int[n];
		for(int i = 0; i < n; i++){
			a[i] = console.nextInt();
		}
		dp[0] = 1;
		int max = 1;
		for(int i = 1;ia[i]){
					dp[i] = Math.max(dp[i], dp[j]+1);
				}
			}
			if(dp[i]>=max){
				max = dp[i];
			}
			
		}
		int[] aa = new int[max];
		aa[max-1] = Integer.MIN_VALUE;
		int m = max;
		for(int i = n-1,j =0; i >=0 ; i--){
			if(dp[i] ==max ){
				//System.out.println(i);
				aa[j] = a[i];
				j++;
				m--;
			}else{
				if(dp[i]==m&&a[i]>aa[j-1]){
					aa[j] = a[i];
					j++;
					m--;
				}
			}
			
		}
		for(int i = max-1;i>=0;i--){
			if(i!=0){
				System.out.print(aa[i]+" ");
			}else{
				System.out.print(aa[i]);
			}
			
		}
		//System.out.println(max);
	}

}


你可能感兴趣的:(计蒜客——求数组最长递减子序列)