Longest Increasing Continuous Subsequence

Question

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.

Tags

Enumeration Dynamic Programming Array

Related Problems

Hard Longest Increasing Continuous subsequence II

Analysis

很直观的思路就是进行两次遍历,第一次从左到右,第二次从右往左,总是检查当前序列是否单调递增,并且记录当前最长的上升序列长度。

Check out the follow up question: Longest Increasing Continuous subsequence II

Solution

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 ans = 1;
        int N = A.length;

        // From left to right
        int len = 1;
        for (int i = 1; i < N; i++) {
            if (A[i] > A[i - 1]) {
                len++;
            } else {
                len = 1;
            }
            ans = Math.max(len, ans);
        }

        // From right to left
        len = 1;
        for (int i = N - 1; i > 0; i--) {
            if (A[i - 1] > A[i]) {
                len++;
            } else {
                len = 1;
            }
            ans = Math.max(len, ans);
        }

        return ans;
    }
}

Last updated