From 072312bd0a4a2b48cc44e44a55c41ae408e8d9c1 Mon Sep 17 00:00:00 2001 From: Jay Gala <57001778+jaygala223@users.noreply.github.com> Date: Sun, 2 Oct 2022 20:19:49 +0530 Subject: [PATCH] Added code for Maximum Subarray Sum (#6536) * Added maximum subarray sum #6519 * fixes: #6519 function names changed as per naming conventions --- other/maximum_subarray.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 other/maximum_subarray.py diff --git a/other/maximum_subarray.py b/other/maximum_subarray.py new file mode 100644 index 000000000..756e00944 --- /dev/null +++ b/other/maximum_subarray.py @@ -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))