LintCode 397 [Longest Increasing Continuous Subsequence]

原题

给定一个整数数组(下标从 0 到 n-1, n 表示整个数组的规模),请找出该数组中的最长上升连续子序列。(最长上升连续子序列可以定义为从右到左或从左到右的序列。)

样例
给定 [5, 4, 2, 1, 3], 其最长上升连续子序列(LICS)为[5, 4, 2, 1], 返回 4.
给定 [5, 1, 2, 3, 4], 其最长上升连续子序列(LICS)为[1, 2, 3, 4], 返回 4.

解题思路

  • 正序逆序各求一个最长序列的值,取最大
  • 一个全局变量res记录最长的长度,一个局部变量temp
  • 当nums[i] > nums[i - 1]时,temp加1
  • 当nums[i] <= nums[i - 1]时,temp重置为1

完整代码

class Solution:
    # @param {int[]} A an array of Integer
    # @return {int}  an integer
    def longestIncreasingContinuousSubsequence(self, A):
        # Write your code here
        return max(self.helper(A), self.helper(A[::-1]))
        
    def helper(self, nums):
        res, temp = 0, 0
        for i in range(len(nums)):
            if nums[i] > nums[i - 1] or i == 0:
                temp += 1
                res = max(res, temp)
            else:
                temp = 1
        return res

你可能感兴趣的:(LintCode 397 [Longest Increasing Continuous Subsequence])