2022-10-28 19:08:41 +00:00
|
|
|
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])
|
2022-10-02 14:49:49 +00:00
|
|
|
10
|
2022-10-28 19:08:41 +00:00
|
|
|
>>> max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4])
|
2022-10-02 14:49:49 +00:00
|
|
|
6
|
|
|
|
"""
|
2022-10-28 19:08:41 +00:00
|
|
|
if not nums:
|
|
|
|
raise ValueError("Input sequence should not be empty")
|
2022-10-02 14:49:49 +00:00
|
|
|
|
|
|
|
curr_max = ans = nums[0]
|
2022-10-28 19:08:41 +00:00
|
|
|
nums_len = len(nums)
|
2022-10-02 14:49:49 +00:00
|
|
|
|
2022-10-28 19:08:41 +00:00
|
|
|
for i in range(1, nums_len):
|
|
|
|
num = nums[i]
|
|
|
|
curr_max = max(curr_max + num, num)
|
2022-10-02 14:49:49 +00:00
|
|
|
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]
|
2022-10-28 19:08:41 +00:00
|
|
|
print(max_subarray_sum(array))
|