Python Program to solve Maximum Subarray Problem using Divide and Conquer


When it is required solve the maximum subarray problem using the divide and conquer method,

Below is the demonstration of the same −

Example

 Live Demo

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)

Output

The list is :
[23, 12, 45, 67, 89, 11]
The maximum contiguous sum is
247

Explanation

  • A method named ‘max_crossing_sum’ is defined that computes the sum of elements on the left part of the list.

  • This is achieved using the ‘max_sub_array_sum’ that helps compute sum of every sub array.

  • Outside the method, a list is defined, and is displayed on the console.

  • The length of the list is determined.

  • The method to calculate the sum of sub array is called by passing this list.

  • The sum is displayed as output on the console

Updated on: 19-Apr-2021

267 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements