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 循环写得很精妙:每次循环,需要判断是否符合 increasing的趋势,如果符合,则计数器加一,否则让计数器归一。下一个循环前,更新 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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,890评论 0 33
  • EasyGive an integer array,find the longest increasing con...
    greatseniorsde阅读 197评论 0 0
  • 如果时光可以倒流记忆可以更改,她会是谁?会在哪里?她是否更愿意把故事的主角换成全新的自己(敢爱敢恨 而不是唯唯诺...
    是我的暖暖呀阅读 376评论 7 3
  • 落霞孤鹜之凄美,残阳断痕之荒凉,戈壁枯木之沉寂,闲愁凄苦,断肠塞外,奈何花落寒风中,夜行霜露正飘零。 浅吟清唱寄愁...
    青春不言败_fcd0阅读 539评论 0 0
  • 我的儿子今天整四个月大了。我们在一起十四个月了,他从一个我肚子里的小小受精卵变成了看见我就咯咯笑的小BABY,我也...
    也木子阅读 525评论 1 2

友情链接更多精彩内容