lintcode-397-最长上升连续子序列

397-最长上升连续子序列

给定一个整数数组(下标从 0 到 n-1, n 表示整个数组的规模),请找出该数组中的最长上升连续子序列。(最长上升连续子序列可以定义为从右到左或从左到右的序列。)

注意事项

time

样例

给定 [5, 4, 2, 1, 3], 其最长上升连续子序列(LICS)为 [5, 4, 2, 1], 返回 4.
给定 [5, 1, 2, 3, 4], 其最长上升连续子序列(LICS)为 [1, 2, 3, 4], 返回 4.

标签

动态规划 数组 枚举法

思路

使用一维数组 dp[i] 记录第 i 位所在的上升连续子序列的长度,则 dp[i] 的最大值就是最长上升连续子序列,但要从左至右和从右至左遍历 2 次数组A

code

class Solution {
public:
    /*
     * @param : An array of Integer
     * @return: an integer
     */
    int longestIncreasingContinuousSubsequence(vector<int> A) {
        // write your code here
        int size = A.size();
        if (size <= 0) {
            return 0;
        }
        vector<int> dp(size, 0);
        dp[0] = 1;
        int maxLeft = dp[0];
        for (int i = 1; i < size; i++) {
            if (A[i] > A[i - 1]) {
                dp[i] = dp[i - 1] + 1;
            }
            else {
                dp[i] = 1;
            }
            maxLeft = max(maxLeft, dp[i]);
        }
        
        dp[size - 1] = 1;
        int maxRight = dp[size - 1];
        for (int i = size - 2; i >= 0; i--) {
            if (A[i] > A[i + 1]) {
                dp[i] = dp[i + 1] + 1;
            }
            else {
                dp[i] = 1;
            }
            maxRight = max(maxRight, dp[i]);
        }
        return max(maxLeft, maxRight);
    }
};
原文地址:https://www.cnblogs.com/libaoquan/p/7349729.html