From 528b1290194da09c2e762c2232502d2cfcdb1e3d Mon Sep 17 00:00:00 2001 From: Pronoy Mandal Date: Sat, 29 Oct 2022 00:38:41 +0530 Subject: [PATCH] Update maximum_subarray.py (#7757) * Update maximum_subarray.py 1. Rectify documentation to indicate the correct output: function doesn't return the subarray, but rather returns a sum. 2. Make the function more Pythonic and optimal. 3. Make function annotation generic i.e. can accept any sequence. 4. Raise value error when the input sequence is empty. * Update maximum_subarray.py 1. Use the conventions as mentioned in pep-0257. 2. Use negative infinity as the initial value for the current maximum and the answer. * Update maximum_subarray.py Avoid type conflict by returning the answer cast to an integer. * Update other/maximum_subarray.py Co-authored-by: Andrey * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update maximum_subarray.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update maximum_subarray.py Remove typecast to int for the final answer Co-authored-by: Andrey Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- other/maximum_subarray.py | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/other/maximum_subarray.py b/other/maximum_subarray.py index 756e00944..1c8c8cabc 100644 --- a/other/maximum_subarray.py +++ b/other/maximum_subarray.py @@ -1,20 +1,26 @@ -def max_subarray(nums: list[int]) -> int: - """ - Returns the subarray with maximum sum - >>> max_subarray([1,2,3,4,-2]) +from collections.abc import Sequence + + +def max_subarray_sum(nums: Sequence[int]) -> int: + """Return the maximum possible sum amongst all non - empty subarrays. + + Raises: + ValueError: when nums is empty. + + >>> max_subarray_sum([1,2,3,4,-2]) 10 - >>> max_subarray([-2,1,-3,4,-1,2,1,-5,4]) + >>> max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4]) 6 """ + if not nums: + raise ValueError("Input sequence should not be empty") curr_max = ans = nums[0] + nums_len = len(nums) - for i in range(1, len(nums)): - if curr_max >= 0: - curr_max = curr_max + nums[i] - else: - curr_max = nums[i] - + for i in range(1, nums_len): + num = nums[i] + curr_max = max(curr_max + num, num) ans = max(curr_max, ans) return ans @@ -23,4 +29,4 @@ def max_subarray(nums: list[int]) -> int: if __name__ == "__main__": n = int(input("Enter number of elements : ").strip()) array = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n] - print(max_subarray(array)) + print(max_subarray_sum(array))