Python实现《算法导论》伪代码:最大子数组问题

一个数组的和最大的非空连续子数组称为该数组的最大子数组。只有当数组中包含负数时,最大子数组问题才有意义。

Python实现代码:

def mid_cross(arr,low,mid,high):
	
	left_sum = -float('inf')
	cal_sum = 0
	for i in range(mid,low-1,-1):
		cal_sum = cal_sum + arr[i] 
		if cal_sum > left_sum:
			left_sum = cal_sum
			max_left = i
			
	right_sum = -float('inf')
	cal_sum = 0
	for i in range(mid+1,high+1):   # error-prone place
		cal_sum = cal_sum + arr[i]
		if cal_sum > right_sum:
			right_sum = cal_sum
			max_right = i
			
	return(max_left,max_right,left_sum + right_sum)

def max_subarray(arr,low,high):
	
	if low == high:
		return(low,high,arr[low])
	else:
		mid = int((low+high)/2)
		left_low,left_high,left_sum = max_subarray(arr,low,mid)
		right_low,right_high,right_sum = max_subarray(arr,mid+1,high)
		cross_low,cross_high,cross_sum = mid_cross(arr,low,mid,high)
		
		if left_sum >= right_sum and left_sum >= cross_sum:
			return(left_low,left_high,left_sum)
		elif right_sum >= left_sum and right_sum >= cross_sum:
			return(right_low,right_high,right_sum)
		else:
			return(cross_low,cross_high,cross_sum)
			
a = [13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7]
h,j,k = max_subarray(a,0,len(a)-1)  #mistake-prone place
print(h,j,k)

'''
输出如下(数组位置下标为从0开始):
7 10 43
'''

你可能感兴趣的:(算法导论,python,最大子数组)