Lintcode:最长上升连续子序列

问题:

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

样例:

样例 1:

输入:[5, 4, 2, 1, 3]
输出:4
解释:
给定 [5, 4, 2, 1, 3],其最长上升连续子序列(LICS)为 [5, 4, 2, 1],返回 4。

样例 2:

输入:[5, 1, 2, 3, 4]
输出:4
解释:
给定 [5, 1, 2, 3, 4],其最长上升连续子序列(LICS)为 [1, 2, 3, 4],返回 4。

python:

class Solution:
    """
    @param A: An array of Integer
    @return: an integer
    """
    def longestIncreasingContinuousSubsequence(self, A):
        # write your code here
        if len(A) == 0 or len(A) == 1:
            return len(A)
        maxLen = 1
        i = 1
        while i < len(A):
            addLen = 1
            subLen = 1
            while i < len(A) and A[i] > A[i-1]:
                addLen += 1
                i += 1
            while i < len(A) and A[i] < A[i-1]:
                subLen += 1
                i += 1
            maxLen = max(maxLen, max(addLen, subLen))
        return maxLen

C++:

class Solution {
public:
    /**
     * @param A: An array of Integer
     * @return: an integer
     */
    int longestIncreasingContinuousSubsequence(vector &A) {
        // write your code here
        if(A.size() == 0 || A.size() == 1)
        {
            return A.size();
        }
        int maxLen = 1;
        int i = 1; 
        while(i < A.size())
        {
            int AddLen = 1;
            int SubLen = 1;
            while(i < A.size() && A[i] > A[i-1])
            {
                AddLen++;
                i++;
            }
            while(i < A.size() && A[i] < A[i-1])
            {
                SubLen++;
                i++;
            }
            maxLen = max(maxLen, max(AddLen, SubLen));
        }
        return maxLen;
    }
};

 

你可能感兴趣的:(Lintcode)