代码随想录算法训练营第五十二天| 300.最长递增子序列,674. 最长连续递增序列,718. 最长重复子数组

代码随想录算法训练营第五十二天

  • 300.最长递增子序列
  • 674. 最长连续递增序列
  • 718. 最长重复子数组

300.最长递增子序列

代码

#  !/usr/bin/env  python
#  -*- coding:utf-8 -*-
# @Time   :  2022.12
# @Author :  hello algorithm!
# @Note   :  https://leetcode.cn/problems/longest-increasing-subsequence/
from typing import List


class Solution:
    """
    dp[i]表示i之前包括i的以nums[i]结尾最长上升子序列的长度
    """

    def lengthOfLIS(self, nums: List[int]) -> int:
        dp = [1] * len(nums)
        if len(nums) <= 1:
            return 1
        result = 0
        for i in range(1, len(nums)):
            for j in range(i):
                if nums[i] > nums[j]:
                    dp[i] = max(dp[i], dp[j] + 1)
                if dp[i] > result:
                    result = dp[i]
        return result


if __name__ == '__main__':
    pass

674. 最长连续递增序列

代码

#  !/usr/bin/env  python
#  -*- coding:utf-8 -*-
# @Time   :  2022.12
# @Author :  hello algorithm!
# @Note   :  https://leetcode.cn/problems/longest-continuous-increasing-subsequence/
from typing import List


class Solution:
    """
    dp[i]表示i之前包括i的以nums[i]结尾的连续递增子序列的长度
    """

    def findLengthOfLCIS(self, nums: List[int]) -> int:
        if len(nums) <= 1:
            return 1
        result = 0
        dp = [1] * len(nums)
        for i in range(1, len(nums)):
            if nums[i] >= nums[i - 1]:
                dp[i] = dp[i - 1] + 1
            if dp[i] > result:
                result = dp[i]
        return result


if __name__ == '__main__':
    nums = [2, 2, 2, 2, 2]
    s = Solution()
    print(s.findLengthOfLCIS(nums))

718. 最长重复子数组

代码

#  !/usr/bin/env  python
#  -*- coding:utf-8 -*-
# @Time   :  2022.12
# @Author :  hello algorithm!
# @Note   :  https://leetcode.cn/problems/maximum-length-of-repeated-subarray/
from typing import List


class Solution:
    def findLength(self, nums1: List[int], nums2: List[int]) -> int:
        dp = [[0 for _ in range(len(nums2) + 1)] for _ in range(len(nums1) + 1)]
        result = 0
        for i in range(1, len(nums1) + 1):
            for j in range(1, len(nums2) + 1):
                if nums1[i - 1] == nums2[j - 1]:
                    dp[i][j] += dp[i - 1][j - 1] + 1
                if dp[i][j] > result:
                    result = dp[i][j]
        return result


if __name__ == '__main__':
    pass

你可能感兴趣的:(算法,leetcode,动态规划)