1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| def enumerate_reversed(sequence, start=None): n = len(sequence)-1 if start is None else start for elem in reversed(sequence): yield n, elem n -= 1 def find_max_crossing_subarray(array, mid): left_max, left_pos, left_sum = array[mid-1], mid-1, 0 for left_elem_idx, left_elem in enumerate_reversed(array[:mid]): left_sum += left_elem if left_sum > left_max: left_pos = left_elem_idx right_max, right_pos, right_sum = array[mid], mid, 0 for right_elem_idx, right_elem in enumerate(array[mid:]): right_sum += right_elem if right_sum > right_max: right_pos = right_elem_idx return array[left_pos:mid+right_pos+1] def find_maximum_subarray(array): if len(array) == 1: return array else: mid = len(array) // 2 left_array = find_maximum_subarray(array[:mid]) right_array = find_maximum_subarray(array[mid:]) cross_array = find_max_crossing_subarray(array, mid)
left_sum, right_sum, cross_sum = sum(left_array), sum(right_array), sum(cross_array) if left_sum > right_sum and left_sum > cross_sum: return left_array elif right_sum > left_sum and right_sum > cross_sum: return right_array return cross_array test_array = [13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7] maximum_array = find_maximum_subarray(test_array) print(maximum_array)
|