LintCode - 最長上升連續(xù)子序列(普通)

版權(quán)聲明:本文為博主原創(chuàng)文章,未經(jīng)博主允許不得轉(zhuǎn)載。

難度:容易
要求:

給定一個整數(shù)數(shù)組(下標(biāo)從 0 到 n-1, n 表示整個數(shù)組的規(guī)模),請找出該數(shù)組中的最長上升連續(xù)子序列。(最長上升連續(xù)子序列可以定義為從右到左或從左到右的序列。)

樣例

給定 [5, 4, 2, 1, 3], 其最長上升連續(xù)子序列(LICS)為 [5, 4, 2, 1], 返回 4.
給定 [5, 1, 2, 3, 4], 其最長上升連續(xù)子序列(LICS)為 [1, 2, 3, 4], 返回 4.

思路

public class Solution {
    /**
     * @param A an array of Integer
     * @return  an integer
     */
    public int longestIncreasingContinuousSubsequence(int[] A) {
        if (A == null || A.length == 0) {
            return 0;
        }
        
        //返回值
        int reValue = 1;
        
        //首先遍歷從左到右
        int len = 1;
        for(int i = 1; i < A.length; i++){
            if(A[i] > A[i - 1]){
                len++;//長度增加
            }else{
                len = 1;//長度為1
            }
            reValue = Math.max(len, reValue);
        }
        
        //再遍歷從右到左
        len = 1;
        for(int i = A.length - 1; i > 0; i--){
            if(A[i - 1] > A[i]){
                len++;
            }else{
                len = 1;
            }
            reValue = Math.max(len, reValue);
        }
        return reValue;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容