674. Longest Continuous Increasing Subsequence
Array, AMateList ·Problem Statement
link: LeetCode.cn LeetCode Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing.
A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], …, nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1].
Example:
Input: nums = [1,3,5,4,7]
Output: 3
Input: nums = [2,2,2,2,2]
Output: 1
Constraints: 1 <= nums.length <= 104 -109 <= nums[i] <= 109
Solution Approach
The solution iteratively expands the right boundary of a sliding window while tracking the longest continuous increasing subsequence, resetting the left boundary whenever the sequence stops increasing.
Algorithm
- Initialize Pointers and Variables: Start with two pointers, l and r, both at the beginning of the array, and initialize a variable res to keep track of the maximum length of any increasing subsequence found.
- Expand the Right Pointer: Move the right pointer r forward while the sequence is strictly increasing (nums[r + 1] > nums[r]). Update the maximum length res when the sequence ends.
- Reset Pointers: Once the sequence stops increasing, move both pointers to the next position (l = r + 1) and repeat the process until the entire array is scanned. Return the maximum length res as the result.
Implement
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
res = 0
n = len(nums)
if not n:
return 0
l, r = 0, 0
if n == 1:
return 1
while r < n - 1:
while r < n - 1 and nums[r + 1] > nums[r]:
r += 1
res = max(res, r - l + 1)
l = r = r + 1
return res