January 15, 2022

674. Longest Continuous Increasing Subsequence

674. Longest Continuous Increasing Subsequence

Solution0. DP

Time=O(n), Space=O(n). Not optimized.

class Solution {
    public int findLengthOfLCIS(int[] nums) {
        int lengthOfLCIS = 1;
        int[] LCIS = new int[nums.length];
        LCIS[0] = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > nums[i - 1]) {
                LCIS[i] = LCIS[i - 1] + 1;
                lengthOfLCIS = Math.max(lengthOfLCIS, LCIS[i]);
            } else {
                LCIS[i] = 1;
            }
        }
        return lengthOfLCIS;
    }
}

Solution1. DP with space optimization

Time=O(n), Space=O(1).
We can make the space consumption more efficient by only recording the latest dp[i].

class Solution {
    public int findLengthOfLCIS(int[] nums) {
        int maxLCIS = 1;
        int curLCIS = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > nums[i - 1]) {
                curLCIS += 1;
                maxLCIS = Math.max(maxLCIS, curLCIS);
            } else {
                curLCIS = 1;
            }
        }
        return maxLCIS;
    }
}
comments powered by Disqus