1.数列的最大子段和
MAX = 100
a = [0 for _ in range(MAX)]
def maxSubSum(a, left, right):
sum = 0
if left == right:
sum = a[left] if a[left] > 0 else 0
else:
center = (left + right) // 2
leftSum = maxSubSum(a, left, center)
rightSum = maxSubSum(a, center + 1, right)
s1 = 0
lefts = 0
for i in range(center, left - 1, -1):
lefts += a[i]
if lefts > s1:
s1 = lefts
s2 = 0
rights = 0
for j in range(center + 1, right + 1, 1):
rights += a[j]
if rights > s2:
s2 = rights
sum = s1 + s2
if sum < leftSum:
sum = leftSum
if sum < rightSum:
sum = rightSum
return sum
def maxSum(a, n):
return maxSubSum(a, 0, n - 1)
if __name__ == '__main__':
n = int(input('请输入数列元素的个数n='))
print('请输入数列元素a[i]=')
for i in range(n):
a[i] = int(input())
print('数组a的最大连续子段和为:', maxSum(a, n))
"""
请输入数列元素的个数n=6
请输入数列元素a[i]=
-2
11
-4
13
-5
-2
数组a的最大连续子段和为: 20
"""
2.最长公共子序列
"""
最长公共子序列
"""
def LCS(s1, s2):
m, n = len(s1), len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i - 1] == s2[j - 1]:
dp[i][j] = 1 + dp[i - 1][j - 1]
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
result = ''
while m != 0 and n != 0:
if s1[m - 1] == s2[n - 1]:
result += s1[m - 1]
m -= 1
n -= 1
else:
if dp[m][n] == dp[m - 1][n]:
m -= 1
else:
n -= 1
return dp[-1][-1], result[::-1]
s1 = input('请输入字符串序列s1:')
s2 = input('请输入字符串序列s2:')
length, result = LCS(s1, s2)
print(f'最长公共子序列为:{result},长度为:{length}')
"""
请输入字符串序列s1:INTHEBEGINNING
请输入字符串序列s2:ALLTHETHINGSARELOST
最长公共子序列为:THEING,长度为:6
"""