Daily question: The length of the longest continuous increasing subsequence

Problem-solving ideas:

  1. max_lenThe variables and are initialized curr_lento 0, respectively representing the length of the longest continuous increasing subsequence and the length of the currently calculating continuous increasing subsequence.
  2. Iterate over the given array, for each element:
  • If the current element is greater than the previous element, it will curr_lenbe incremented by one.
  • Otherwise, curr_lenreset to 1 and start calculating the length of successively increasing subsequences again.
  • Update max_lento the current larger value of curr_lenand max_len.
  1. return max_len.
    Code implementation and comments:
def find_length_of_lcis(nums):
    # 初始化变量
    max_len = 0
    curr_len = 0
    
    # 遍历数组
    for i in range(len(nums)):
        if i == 0 or nums[i] > nums[i-1]:
            # 当前元素大于前一个元素,增加当前连续递增子序列的长度
            curr_len += 1
        else:
            # 当前元素小于等于前一个元素,重置当前连续递增子序列的长度为 1
            curr_len = 1
        
        # 更新最大长度
        max_len = max(max_len, curr_len)
    
    return max_len

# 测试
nums = [1, 3, 5, 4, 7]
result = find_length_of_lcis(nums)
print(result)  # 输出: 3,因为最长连续递增子序列为 [1, 3, 5]

nums = [2, 2, 2, 2, 2]
result = find_length_of_lcis(nums)
print(result)  # 输出: 1,因为最长连续递增子序列为 [2]

The time complexity of this algorithm is O(n), where n is the length of the array. During the execution of the algorithm, we only need to traverse the array once, and for each element, comparison and update operations can be performed in constant time. Therefore, the time complexity of this algorithm is linear.

Guess you like

Origin blog.csdn.net/qq_29669259/article/details/131592183