From ca5d3a5a556711225ad92a0f88bee30181a3df54 Mon Sep 17 00:00:00 2001 From: Divlo Date: Sun, 1 May 2022 18:44:07 +0200 Subject: [PATCH] feat(solutions): add `maximum-subarray-sum/python/linear` --- .../solutions/python/linear/README.md | 3 +++ .../solutions/python/linear/solution.py | 26 +++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 challenges/maximum-subarray-sum/solutions/python/linear/README.md create mode 100644 challenges/maximum-subarray-sum/solutions/python/linear/solution.py diff --git a/challenges/maximum-subarray-sum/solutions/python/linear/README.md b/challenges/maximum-subarray-sum/solutions/python/linear/README.md new file mode 100644 index 0000000..8630a8f --- /dev/null +++ b/challenges/maximum-subarray-sum/solutions/python/linear/README.md @@ -0,0 +1,3 @@ +# maximum-subarray-sum/python/linear + +Created by [@Divlo](https://github.com/Divlo) on 1 May 2022. diff --git a/challenges/maximum-subarray-sum/solutions/python/linear/solution.py b/challenges/maximum-subarray-sum/solutions/python/linear/solution.py new file mode 100644 index 0000000..a5237dd --- /dev/null +++ b/challenges/maximum-subarray-sum/solutions/python/linear/solution.py @@ -0,0 +1,26 @@ +import sys + + +def maximum_subarray_sum_linear(array: list[int]) -> int: + """ + Time complexity: O(array_length) + + We loop through the array and for each array position, we calculate the maximum sum of a subarray that ends at that position. After this, the answer for the problem is the maximum of those sums. + """ + if len(array) == 0: + return 0 + best_sum = array[0] + length = len(array) + sum = 0 + for i in range(length): + sum = max(array[i], sum + array[i]) + best_sum = max(best_sum, sum) + return best_sum + + +numbers: list[int] = [] +for value in sys.stdin: + numbers.append(int(value.rstrip('\n'))) + +numbers = numbers[1:] +print(maximum_subarray_sum_linear(numbers))