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.

  1. rolling array and dp
    1. state f[n] represents what is the longest continuous subsequence ends at position n
    2. formular: f[n] = if A[n - 1] < A[n] : f[n] = f[n - 1] + 1 else 1
    3. init: f[0] = 1 maxValue = 1
    4. order, from left to right and right to left
public class Solution {
    /**
     * @param A an array of Integer
     * @return  an integer
     */
    public int longestIncreasingContinuousSubsequence(int[] A) {
        // Write your code here
        if (A == null || A.length == 0) {
            return 0;
        }

        int[] f = new int[2];
        f[0] = 1;
        int max = 1; 
        //f[n] is the longest continuous subsequence at n
        //f[n] = A[n - 1] = A[n] - 1, f[n] = f[n - 1]  + 1
        //       f[n] = 1

        int i;
        for (i = 1; i < A.length; i++) {
            if (A[i - 1] < A[i]) {
                if (i % 2 == 0) {
                    f[i % 2] = f[(i % 2) + 1] + 1;
                } else {
                    f[i % 2] = f[(i % 2) - 1] + 1;
                }

            } else {
                f[i % 2] = 1;
            }

            max = Math.max(max, f[i % 2]);
        }

        f[0] = 1;
        for (i = 1; i < A.length; i++) {
            if (A[i- 1] > A[i]) {
                if (i % 2 == 0) {
                    f[i % 2] = f[(i % 2) + 1] + 1;
                } else {
                    f[i % 2] = f[(i % 2) - 1] + 1;
                }
            } else {
                f[i % 2] = 1;
            }

            max = Math.max(max, f[i % 2]);
        }

        return max;

    }
}

results matching ""

    No results matching ""