LC 674. Longest Continuous Increasing Subsequence

Sarthak Sehgal · March 27, 2020

Solution

The question is pretty common and straightforward. We keep track of two variables, res and currLen. res stores the size of longest increasing subarray found yet and currLen stores the current length of increasing subsequence. Iterate through the array and if array[i] > array[i-1] then increase currLen else if array[i]<=array[i-1] then this element may be the starting point of another increasing subarray so currLen=1. At every step, res stores the maximum length of increasing subarray so res = max(res, currLen).

int findLengthOfLCIS(vector<int>& nums) {
    // sanity check
    if (nums.size()==0)
        return 0;

    int res=1, currLen=1;
    for (int i=1; i<nums.size(); i++) {
        if (nums[i]>nums[i-1])
            currLen++;
        else
            currLen = 1;

        res = max(res, currLen);
    }

    return res;
}

Time complexity: O(n)
Space complexity: O(1)

Twitter, Facebook