mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-27 15:01:08 +00:00
528b129019
* 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>
33 lines
811 B
Python
33 lines
811 B
Python
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_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, nums_len):
|
|
num = nums[i]
|
|
curr_max = max(curr_max + num, num)
|
|
ans = max(curr_max, ans)
|
|
|
|
return ans
|
|
|
|
|
|
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_sum(array))
|