题目:

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

样例

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

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

解题:

这个直接找就可以了,最长的升序,和最长的降序,再求最大值,时间复杂度O(N)

Java程序:

public class Solution {
    /**
     * @param A an array of Integer
     * @return  an integer
     */
    public int longestIncreasingContinuousSubsequence(int[] A) {
        // Write your code here
        int left = Integer.MIN_VALUE;
        int right = Integer.MIN_VALUE;
        int m = A.length;
        int tmp1 = 1;
        int tmp2 = 1;
        if (m==0)
            return 0;
        for(int i = 0; i<m-1 ;i++){
            if (A[i] <= A[i+1]){
                tmp1++;
            }else{
                left = left>tmp1?left:tmp1;
                tmp1 = 1;
            }
            if (A[i] >= A[i+1]){
                tmp2 ++;
            }else{
                right = right>tmp2?right:tmp2;
                tmp2 = 1;
            }
        }
        left = left>tmp1?left:tmp1;
        right = right>tmp2?right:tmp2;
        return left>right?left:right;
    }
}
View Code

总耗时: 6578 ms

Python程序:

class Solution:
    # @param {int[]} A an array of Integer
    # @return {int}  an integer
    def longestIncreasingContinuousSubsequence(self, A):
        # Write your code here
        m = len(A)
        if m ==0:
            return 0
        left = 0
        right = 0
        tmp1 = 1
        tmp2 = 1 
        for i in range(m-1):
            if A[i]<= A[i+1]:
                tmp1+=1
            else:
                left = max(left,tmp1)
                tmp1 = 1
            if A[i]>= A[i+1]:
                tmp2+=1
            else:
                right = max(right,tmp2)
                tmp2 = 1
        left = max(tmp1,left)
        right = max(tmp2,right)
        return max(left, right)
View Code

总耗时: 546 ms