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 <Cjkjvfnby@gmail.com>

* [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 <Cjkjvfnby@gmail.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
Pronoy Mandal 2022-10-29 00:38:41 +05:30 committed by GitHub
parent d9efd7e25b
commit 528b129019
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,20 +1,26 @@
def max_subarray(nums: list[int]) -> int: from collections.abc import Sequence
"""
Returns the subarray with maximum sum
>>> max_subarray([1,2,3,4,-2]) 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 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 6
""" """
if not nums:
raise ValueError("Input sequence should not be empty")
curr_max = ans = nums[0] curr_max = ans = nums[0]
nums_len = len(nums)
for i in range(1, len(nums)): for i in range(1, nums_len):
if curr_max >= 0: num = nums[i]
curr_max = curr_max + nums[i] curr_max = max(curr_max + num, num)
else:
curr_max = nums[i]
ans = max(curr_max, ans) ans = max(curr_max, ans)
return ans return ans
@ -23,4 +29,4 @@ def max_subarray(nums: list[int]) -> int:
if __name__ == "__main__": if __name__ == "__main__":
n = int(input("Enter number of elements : ").strip()) n = int(input("Enter number of elements : ").strip())
array = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n] array = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n]
print(max_subarray(array)) print(max_subarray_sum(array))