使用分治法解决最大子数组问题的 Python 程序
当需要使用分治法解决最大子数组问题时,
以下是对它的演示 -
示例
def max_crossing_sum(my_array, low, mid, high):
sum_elements = 0
sum_left_elements = -10000
for i in range(mid, low-1, -1):
sum_elements = sum_elements + my_array[i]
if (sum_elements > sum_left_elements):
sum_left_elements = sum_elements
sum_elements = 0
sum_right_elements = -1000
for i in range(mid + 1, high + 1):
sum_elements = sum_elements + my_array[i]
if (sum_elements > sum_right_elements):
sum_right_elements = sum_elements
return max(sum_left_elements + sum_right_elements, sum_left_elements, sum_right_elements)
def max_sub_array_sum(my_array, low, high):
if (low == high):
return my_array[low]
mid = (low + high) // 2
return max(max_sub_array_sum(my_array, low, mid), max_sub_array_sum(my_array, mid+1, high), max_crossing_sum(my_array, low, mid, high))
my_list = [23, 12, 45, 67, 89, 11]
list_length = len(my_list)
print("The list is :")
print(my_list)
max_sum = max_sub_array_sum(my_list, 0, list_length-1)
print("The maximum contiguous sum is ")
print(max_sum)输出
The list is : [23, 12, 45, 67, 89, 11] The maximum contiguous sum is 247
说明
定义了一个名为“max_crossing_sum”的方法,它计算列表中左侧元素的总和。
这是使用“max_sub_array_sum”实现的,它有助于计算每个子数组的总和。
在方法外,定义了一个列表并将其显示在控制台上。
确定列表的长度。
通过传递此列表来调用计算子数组总和的方法。
该总和作为输出显示在控制台上
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP