1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2024-11-09 22:08:58 +01:00

feat(solutions): add maximum-subarray-sum/python/recursive

This commit is contained in:
Divlo 2022-05-01 18:45:28 +02:00
parent ca5d3a5a55
commit a6fee4de05
No known key found for this signature in database
GPG Key ID: 8F9478F220CE65E9
2 changed files with 44 additions and 0 deletions

View File

@ -0,0 +1,3 @@
# maximum-subarray-sum/python/recursive
Created by [@Divlo](https://github.com/Divlo) on 1 May 2022.

View File

@ -0,0 +1,41 @@
import sys
def maximum_subarray_sum_recursive(array: list[int]) -> int:
"""
Time complexity: O((array_length) * log(array_length))
"""
def maximum_subarray_sum(array: list[int], left: int, right):
if len(array) == 0:
return 0
if right == left:
return array[left]
middle = (left + right) // 2
left_maximum_sum = array[middle]
total = 0
for i in range(middle, left - 1, -1):
total += array[i]
if total > left_maximum_sum:
left_maximum_sum = total
right_maximum_sum = array[middle + 1]
total = 0
for i in range(middle + 1, right + 1):
total += array[i]
if total > right_maximum_sum:
right_maximum_sum = total
maximum_sum = max(maximum_subarray_sum(array, left, middle), maximum_subarray_sum(array, middle + 1, right))
return max(maximum_sum, left_maximum_sum + right_maximum_sum)
return maximum_subarray_sum(array, 0, len(array) - 1)
numbers: list[int] = []
for value in sys.stdin:
numbers.append(int(value.rstrip('\n')))
numbers = numbers[1:]
print(maximum_subarray_sum_recursive(numbers))