|
| 1 | +""" |
| 2 | +Given a array of length n, max_sub_array_sum() finds the maximum of sum of contiguous sub-array using divide and conquer method. |
| 3 | +
|
| 4 | +Time complexity : O(n log n) |
| 5 | +
|
| 6 | +Ref : INTRODUCTION TO ALGORITHMS THIRD EDITION (section : 4, sub-section : 4.1, page : 70) |
| 7 | +
|
| 8 | +""" |
| 9 | + |
| 10 | + |
| 11 | +defmax_sum_from_start(array): |
| 12 | +""" This function finds the maximum contiguous sum of array from 0 index |
| 13 | +
|
| 14 | + Parameters : |
| 15 | + array (list[int]) : given array |
| 16 | +
|
| 17 | + Returns : |
| 18 | + max_sum (int) : maximum contiguous sum of array from 0 index |
| 19 | +
|
| 20 | + """ |
| 21 | +array_sum=0 |
| 22 | +max_sum=float("-inf") |
| 23 | +fornuminarray: |
| 24 | +array_sum+=num |
| 25 | +ifarray_sum>max_sum: |
| 26 | +max_sum=array_sum |
| 27 | +returnmax_sum |
| 28 | + |
| 29 | + |
| 30 | +defmax_cross_array_sum(array,left,mid,right): |
| 31 | +""" This function finds the maximum contiguous sum of left and right arrays |
| 32 | +
|
| 33 | + Parameters : |
| 34 | + array, left, mid, right (list[int], int, int, int) |
| 35 | +
|
| 36 | + Returns : |
| 37 | + (int) : maximum of sum of contiguous sum of left and right arrays |
| 38 | +
|
| 39 | + """ |
| 40 | + |
| 41 | +max_sum_of_left=max_sum_from_start(array[left:mid+1][::-1]) |
| 42 | +max_sum_of_right=max_sum_from_start(array[mid+1:right+1]) |
| 43 | +returnmax_sum_of_left+max_sum_of_right |
| 44 | + |
| 45 | + |
| 46 | +defmax_sub_array_sum(array,left,right): |
| 47 | +""" This function finds the maximum of sum of contiguous sub-array using divide and conquer method |
| 48 | +
|
| 49 | + Parameters : |
| 50 | + array, left, right (list[int], int, int) : given array, current left index and current right index |
| 51 | +
|
| 52 | + Returns : |
| 53 | + int : maximum of sum of contiguous sub-array |
| 54 | +
|
| 55 | + """ |
| 56 | + |
| 57 | +# base case: array has only one element |
| 58 | +ifleft==right: |
| 59 | +returnarray[right] |
| 60 | + |
| 61 | +# Recursion |
| 62 | +mid= (left+right)//2 |
| 63 | +left_half_sum=max_sub_array_sum(array,left,mid) |
| 64 | +right_half_sum=max_sub_array_sum(array,mid+1,right) |
| 65 | +cross_sum=max_cross_array_sum(array,left,mid,right) |
| 66 | +returnmax(left_half_sum,right_half_sum,cross_sum) |
| 67 | + |
| 68 | + |
| 69 | +array= [-2,-5,6,-2,-3,1,5,-6] |
| 70 | +array_length=len(array) |
| 71 | +print("Maximum sum of contiguous subarray:",max_sub_array_sum(array,0,array_length-1)) |
| 72 | + |