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] <= 109g.
Solution Approach
Use a sliding window approach with two pointers to track and update the length of the longest continuous increasing subsequence by expanding the right pointer until the sequence stops increasing, then adjust the left pointer and continue.
Algorithm
- Initialize Pointers: Use two pointers, l (left) and r (right), to represent the current window of the increasing subsequence.
- Expand and Update: Move the right pointer r to expand the window while the sequence is strictly increasing, and update the maximum length of the subsequence found (res).
- Adjust Window: When the sequence stops increasing, update res with the length of the current subsequence, and shift both pointers to start a new window from the next position (l = r = r + 1).
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