Leetcode 674. Longest Continuous Increasing Subsequence
Given an unsorted array of integers, find the length of the longest continuous increasing subsequence (subarray).
Input: [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. Even though [1,3,5,7] is an increasing subsequence, it’s not continuous as elements 5 and 7 are separated by 4.
Input: [2,2,2,2,2]
Output: 1
Explanation: The longest continuous increasing subsequence is [2], its length is 1.
This problem can be effectively solved using a single pass (O(n) time complexity) algorithm. We can maintain a variable to keep track of the current length of the increasing subsequence and another variable to store the maximum length found so far.
maxLen
and currLen
, to 1 since the minimum length for any subsequence with at least one element is 1.currLen
by 1.currLen
with maxLen
and update maxLen
if necessary, then reset currLen
to 1.currLen
and maxLen
in case the longest subsequence is at the end of the array.maxLen
.#include <vector>
#include <algorithm> // For std::max
class Solution {
public:
int findLengthOfLCIS(std::vector<int>& nums) {
if (nums.empty()) return 0;
int maxLen = 1;
int currLen = 1;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] > nums[i - 1]) {
++currLen;
} else {
maxLen = std::max(maxLen, currLen);
currLen = 1;
}
}
// Final comparison in case the longest sequence ends at the last element
maxLen = std::max(maxLen, currLen);
return maxLen;
}
};
The time complexity for this algorithm is O(n), where n
is the size of the input array. This is because we only make a single pass through the array.
The space complexity is O(1) since we are only using a fixed amount of extra space regardless of the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?