Khi cần giải bài toán Maximum Subarray bằng chia để trị (Divide and Conquer):
Dưới đây minh họa:
Ví dụ
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)
Kết quả
The list is : [23, 12, 45, 67, 89, 11] The maximum contiguous sum is 247
Giải thích
- Phương thức 'max_crossing_sum' tính tổng phần tử bên trái danh sách.
- Được thực hiện qua 'max_sub_array_sum' tính tổng mọi mảng con.
- Ngoài phương thức, danh sách được định nghĩa và hiển thị.
- Độ dài danh sách được xác định.
- Phương thức tính tổng mảng con được gọi truyền danh sách.
- Tổng được hiển thị output.