当前位置:网站首页>Leetcode 674 longest incrementing substring

Leetcode 674 longest incrementing substring

2022-06-12 17:59:00 zhuxiaohai68

Given an unordered array of integers , Find the longest and Successive increasing subsequences , And return the length of the sequence .

Successive increasing subsequences It can be made up of two subscripts l and r(l < r) determine , If for each l <= i < r, There are nums[i] < nums[i + 1] , So the subsequence [nums[l], nums[l + 1], …, nums[r - 1], nums[r]] It's a continuous increasing subsequence .

Example 1:

Input :nums = [1,3,5,4,7]
Output :3
explain : The longest continuous increasing sequence is [1,3,5], The length is 3.
Even though [1,3,5,7] It's also a subsequence of ascending order , But it's not continuous , because 5 and 7 In the original array is 4 separate .
Example 2:

Input :nums = [2,2,2,2,2]
Output :1
explain : The longest continuous increasing sequence is [2], The length is 1.

It can be understood with the idea of dynamic programming . That's to say dp[i] Representative to nums[i] The longest incrementing suffix at the end .

  1. If nums[i] > nums[i-1] be dp[i] = [i-1] + 1
  2. otherwise ,nums[i-1] and nums[i] Cannot form an increasing relationship , With nums[i] The longest incrementing suffix at the end is 1, That is to say nums[i] In itself

The boundary conditions dp[i]=1, That is, the longest incrementing suffix ending in any character can be the smallest 1

class Solution(object):
    def findLengthOfLCIS(self, nums):
        """ :type nums: List[int] :rtype: int """
        n = len(nums)
        dp = [1]*n
        for i in range(n):
            if i > 0 and nums[i] > nums[i-1]:
                dp[i] = dp[i-1] + 1
        return max(dp)

class Solution(object):
    def findLengthOfLCIS(self, nums):
        """ :type nums: List[int] :rtype: int """
        n = len(nums)
        start = 0
        tot = 1
        for i in range(n):
            if i > 0 and nums[i] > nums[i-1]:
                pass
            else:
                start = i 
            tot = max(tot, i-start+1)
        return tot 

                
原网站

版权声明
本文为[zhuxiaohai68]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121751158845.html