1299--最長上升子序列 動態規劃(java)

Submit Statistic Discuss 
Problem Description
一個數的序列bi,當b1 < b2 < ... < bS的時候,我們稱這個序列是上升的。對於給定的一個序列(a1, a2, ..., aN),我們可以得到一些上升的子序列(ai1, ai2, ..., aiK),這裏1<= i1 < i2 < ... < iK <= N。比如,對於序列(1, 7, 3, 5, 9, 4, 8),有它的一些上升子序列,如(1, 7), (3, 4, 8)等等。這些子序列中最長的長度是4,比如子序列(1, 3, 5, 8)。

你的任務,就是對於給定的序列,求出最長上升子序列的長度。 
Input
輸入的第一行是序列的長度N (1 <= N <= 1000)。第二行給出序列中的N個整數,這些整數的取值範圍都在0到10000。 
Output
最長上升子序列的長度。 
Sample Input
7
1 7 3 5 9 4 8
Sample Output
4

dp[i] = 前面value值中小於當前value值的dp最大值+1。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int a[] = new int[n];
		for(int i = 0;i<n;i++) {
			a[i] = sc.nextInt();
		}
        int[] dp = new int[a.length];
        int res = 0;

        for (int i = 0; i < a.length; i++) {
            dp[i] = 1;
            for (int j = 0; j <= i; j++) {
                if (a[j] < a[i]) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
            res = Math.max(res, dp[i]);
        }

        System.out.println(res);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章