From 0d5eca3a74480961f6bab46bb8e8cb1aba5bae92 Mon Sep 17 00:00:00 2001 From: Pronoy Mandal Date: Fri, 28 Oct 2022 00:26:29 +0530 Subject: [PATCH 1/2] 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 function annotation generic i.e. it can accept any iterable nums. 3. Raise value error when the input iterable is empty. --- other/maximum_subarray.py | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/other/maximum_subarray.py b/other/maximum_subarray.py index 756e009444fe..3fe0af3ac5de 100644 --- a/other/maximum_subarray.py +++ b/other/maximum_subarray.py @@ -1,20 +1,24 @@ -def max_subarray(nums: list[int]) -> int: +from typing import Iterable + + +def max_subarray_sum(nums: Iterable[int]) -> int: """ - Returns the subarray with maximum sum - >>> max_subarray([1,2,3,4,-2]) + Raises: + ValueError: when nums is empty. + + Returns the maximum possible sum amongst all non - empty subarrays + >>> 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 iterable should not be empty') curr_max = ans = nums[0] - for i in range(1, len(nums)): - if curr_max >= 0: - curr_max = curr_max + nums[i] - else: - curr_max = nums[i] - + for num in nums[1:]: + curr_max = max(curr_max + num, num) ans = max(curr_max, ans) return ans @@ -23,4 +27,5 @@ 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)) + From 2c71005ca3bf78e443df27613a7b2e64d7755b58 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 27 Oct 2022 19:06:50 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- other/maximum_subarray.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/other/maximum_subarray.py b/other/maximum_subarray.py index 3fe0af3ac5de..ad07417a3564 100644 --- a/other/maximum_subarray.py +++ b/other/maximum_subarray.py @@ -1,4 +1,4 @@ -from typing import Iterable +from collections.abc import Iterable def max_subarray_sum(nums: Iterable[int]) -> int: @@ -13,7 +13,7 @@ def max_subarray_sum(nums: Iterable[int]) -> int: 6 """ if not nums: - raise ValueError('Input iterable should not be empty') + raise ValueError("Input iterable should not be empty") curr_max = ans = nums[0] @@ -28,4 +28,3 @@ def max_subarray_sum(nums: Iterable[int]) -> int: n = int(input("Enter number of elements : ").strip()) array = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n] print(max_subarray_sum(array)) -