mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Added code for Maximum Subarray Sum (#6536)
* Added maximum subarray sum #6519 * fixes: #6519 function names changed as per naming conventions
This commit is contained in:
parent
c9f1d09e1a
commit
072312bd0a
26
other/maximum_subarray.py
Normal file
26
other/maximum_subarray.py
Normal file
|
@ -0,0 +1,26 @@
|
|||
def max_subarray(nums: list[int]) -> int:
|
||||
"""
|
||||
Returns the subarray with maximum sum
|
||||
>>> max_subarray([1,2,3,4,-2])
|
||||
10
|
||||
>>> max_subarray([-2,1,-3,4,-1,2,1,-5,4])
|
||||
6
|
||||
"""
|
||||
|
||||
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]
|
||||
|
||||
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(array))
|
Loading…
Reference in New Issue
Block a user