Longest Increasing Continuous Subsequence

Give an integer array,find the longest increasing continuous subsequence in this array.
An increasing continuous subsequence:
Can be from right to left or from left to right.
Indices of the integers in the subsequence should be continuous.

** Notice
O(n) time and O(1) extra space.

Example
For [5, 4, 2, 1, 3], the LICS is [5, 4, 2, 1], return 4.
For [5, 1, 2, 3, 4], the LICS is [1, 2, 3, 4], return 4.

注意:
這個 for 循環(huán)寫得很精妙:每次循環(huán),需要判斷是否符合 increasing的趨勢,如果符合,則計數(shù)器加一,否則讓計數(shù)器歸一。下一個循環(huán)前,更新 answer,即記錄目前符合條件的最長子串的長度。

public class Solution {
    /**
     * @param A an array of Integer
     * @return  an integer
     */
    public int longestIncreasingContinuousSubsequence(int[] A) {
        // Write your code here
        
        if (A.length <= 1) return A.length;
        
        int answer = 1;
        int n = A.length;
        int length = 1;
        // from left to right
        for (int i = 1; i < n; i++) {
 
            if (A[i] > A[i - 1]) {
                length++;
            } else {
                length = 1;
            }
            answer = Math.max(answer, length);
        }
        length = 1;
        // from right to left
        for (int i = n - 2; i >= 0; i--) {
            if (A[i] > A[i+1]) {
                length++;
            } else {
                length = 1;
            }
            answer = Math.max(answer, length);
        }  
        return answer;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,916評論 0 33
  • EasyGive an integer array,find the longest increasing con...
    greatseniorsde閱讀 197評論 0 0
  • 如果時光可以倒流記憶可以更改,她會是誰?會在哪里?她是否更愿意把故事的主角換成全新的自己(敢愛敢恨 而不是唯唯諾...
    是我的暖暖呀閱讀 383評論 7 3
  • 落霞孤鶩之凄美,殘陽斷痕之荒涼,戈壁枯木之沉寂,閑愁凄苦,斷腸塞外,奈何花落寒風(fēng)中,夜行霜露正飄零。 淺吟清唱寄愁...
    青春不言敗_fcd0閱讀 540評論 0 0
  • 我的兒子今天整四個月大了。我們在一起十四個月了,他從一個我肚子里的小小受精卵變成了看見我就咯咯笑的小BABY,我也...
    也木子閱讀 542評論 1 2

友情鏈接更多精彩內(nèi)容