Solve Maximum Subarray Problem Using Kadane's Algorithm in Python
When it is required to find the maximum sub array using Kadane’s algorithm, a method is defined that helps find the maximum of the sub array. Iterators are used to keep track of the maximum sub array.
Below is the demonstration of the same −
Example
def find_max_sub_array(my_list, beg, end): max_end_at_i = max_seen_till_now = my_list[beg] max_left_at_i = max_left_till_now = beg max_right_till_now = beg + 1 for i in range(beg + 1, end): if max_end_at_i > 0: max_end_at_i += my_list[i] else: max_end_at_i = my_list[i] max_left_at_i = i if max_end_at_i > max_seen_till_now: max_seen_till_now = max_end_at_i max_left_till_now = max_left_at_i max_right_till_now = i + 1 return max_left_till_now, max_right_till_now, max_seen_till_now my_list = input('Enter the list of numbers... ') my_list = my_list.split() my_list = [int(x) for x in my_list] beg, end, max_val = find_max_sub_array(my_list, 0, len(my_list)) print('The maximum subarray begins at index {}, ends at index {}' ' and its sum is {}.'.format(beg, end - 1, max_val))
Output
Enter the list of numbers... 2 5 7 12 6 8 The maximum subarray begins at index 0, ends at index 5 and its sum is 40.
Explanation
A method named ‘find_max_sub_array’ is defined that takes three parameters.
The maximum sub array within a given range is found.
It returns a tuple where the left, right indices of the maximum sub array are returned along with its sum.
A loop is used to keep a check on the maximum sub array that ends at index i.
This is the maximum of all sub arrays.
The method also keeps track of maximum sum of the sub array seen until now, as the loop iterates through the left and right indices.
Outside the method, the list of numbers is taken as input by the user.
This is passed as a parameter to the method.
It is displayed as output on the console.