674. Longest Continuous Increasing Subsequence
https://leetcode.com/problems/longest-continuous-increasing-subsequence/description/
Given an unsorted array of integers, find the length of longest continuous
increasing subsequence (subarray).
Example 1:
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 also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4.
Example 2:
Input: [2,2,2,2,2]
Output: 1
Explanation: The longest continuous increasing subsequence is [2], its length is 1.
Note: Length of the array will not exceed 10,000.
Thoughts
返回数组中最长的递增子数组长度。argmax + subarray => DP或dynamic window。以nums[i]为底,action为是否与前面的拼接,dp存以nums[i]为底最长长度。
Code
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
if len(nums) == 0: return 0
dp, res = 1, 1
for i in range(1, len(nums)):
dp = 1 if nums[i] <= nums[i - 1] else dp + 1
res = max(res, dp)
return res
class Solution {
public int findLengthOfLCIS(int[] nums) {
int max = 0;
for (int i = 0, count = 0; i < nums.length; i++) {
count++;
if (i == nums.length - 1 || nums[i] >= nums[i + 1]) {
max = Math.max(max, count);
count = 0;
}
}
return max;
}
}
Analysis
时间复杂度O(N), 空间O(1).
Last updated
Was this helpful?