最大连续子数组:
问题:
给定n个整数(可能为负数)组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的子段和的最大值。当所给的整数均为负数时定义子段和为0,依此定义,所求的最优值为: Max{0,a[i]+a[i+1]+…+a[j]},1<=i<=j<=n
例如,当(a[1],a[2],a[3],a[4],a[5],a[6])=(-2,11,-4,13,-5,-2)时,最大子段和为20。
分治法:
def Max_cross_sum(list1,left,mid,right):
left_sum = 0
right_sum = 0
temp = 0
mid_1 = mid
while mid_1>=left:
temp += list1[mid_1]
left_sum = max(left_sum,temp)
mid_1 -= 1
temp = 0
mid_1 = mid + 1
while mid_1<=right:
temp += list1[mid_1]
right_sum = max(right_sum,temp)
mid_1 += 1
return left_sum+right_sum
def Max_sum(list1,left,right):
if left == right:
return list1[left]
mid = (left+right)//2
left_sum = Max_sum(list1,left,mid)
right_sum = Max_sum(list1,mid+1,right)
cross_sum = Max_cross_sum(list1,left,mid,right)
return max(left_sum,max(right_sum,cross_sum))
list1 = [-2,1,-3,4,-10,2,10,-5,6]
Max_sum(list1,0,len(list1)-1)
动态规划法:
def Max_sum(lis1):
temp = 0
max_sum = 0
for cnt in list1:
temp = max(temp+cnt,cnt)
max_sum = max(max_sum,temp)
return max_sum
list1 = [-2,1,-3,4,-1,2,10,-5,1]
Max_sum(list1)