Skip to content

Update maximum_subarray.py #7750

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 15 additions & 11 deletions other/maximum_subarray.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
def max_subarray(nums: list[int]) -> int:
from collections.abc 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
Expand All @@ -23,4 +27,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))