Skip to content

Commit 072312b

Browse files
authored
Added code for Maximum Subarray Sum (#6536)
* Added maximum subarray sum #6519 * fixes: #6519 function names changed as per naming conventions
1 parent c9f1d09 commit 072312b

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Diff for: other/maximum_subarray.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
def max_subarray(nums: list[int]) -> int:
2+
"""
3+
Returns the subarray with maximum sum
4+
>>> max_subarray([1,2,3,4,-2])
5+
10
6+
>>> max_subarray([-2,1,-3,4,-1,2,1,-5,4])
7+
6
8+
"""
9+
10+
curr_max = ans = nums[0]
11+
12+
for i in range(1, len(nums)):
13+
if curr_max >= 0:
14+
curr_max = curr_max + nums[i]
15+
else:
16+
curr_max = nums[i]
17+
18+
ans = max(curr_max, ans)
19+
20+
return ans
21+
22+
23+
if __name__ == "__main__":
24+
n = int(input("Enter number of elements : ").strip())
25+
array = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n]
26+
print(max_subarray(array))

0 commit comments

Comments
 (0)