class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
#dp[i][j] 以i-1 和j-1字符结尾的两个序列拥有的最长公共子序列长度
#
dp = [[0]*(len(text1) + 1) for _ in range(len(text2) + 1)]
result = 0
for i in range(1, len(text2) + 1):
for j in range(1, len(text1) + 1):
if text2[i - 1] == text1[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else: #不相等的情况要考虑是因为本题可以不连续,所以在不连续的时候要把之前的最大值保留下来
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j])
if dp[i][j] > result:
result = dp[i][j]
return result
#不相等的情况要考虑是因为本题可以不连续,所以在不连续的时候要把之前的最大值保留下来
class Solution:
def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
dp = [[0]*(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
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
if dp[i][j] > result:
result = dp[i][j]
return result
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
#dp[i]: 以i结尾的数组最大和
#dp[i] = max(nums[i], dp[i - 1] + nums[i])
dp = [0] * (len(nums))
dp[0] = nums[0]
result = dp[0]
for i in range(1, len(nums)):
dp[i] = max(nums[i], dp[i - 1] + nums[i])
if dp[i] > result:
result = dp[i]
return result