From e2fb555163650c974e00302c47147c7eefac6b43 Mon Sep 17 00:00:00 2001 From: jaygala Date: Sun, 2 Oct 2022 16:49:41 +0530 Subject: [PATCH 1/2] Added maximum subarray sum #6519 --- 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 000000000000..be0932d87d96 --- /dev/null +++ b/other/maximum_subarray.py @@ -0,0 +1,26 @@ +def maxSubArray(nums: list[int]) -> int: + """ + Returns the subarray with maximum sum + >>> maxSubArray([1,2,3,4,-2]) + 10 + >>> maxSubArray([-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(maxSubArray(array)) From f95338c3afd043fc2b4328b4c31024e2b9d2d8c1 Mon Sep 17 00:00:00 2001 From: jaygala Date: Sun, 2 Oct 2022 17:03:26 +0530 Subject: [PATCH 2/2] fixes: #6519 function names changed as per naming conventions --- other/maximum_subarray.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/other/maximum_subarray.py b/other/maximum_subarray.py index be0932d87d96..756e009444fe 100644 --- a/other/maximum_subarray.py +++ b/other/maximum_subarray.py @@ -1,9 +1,9 @@ -def maxSubArray(nums: list[int]) -> int: +def max_subarray(nums: list[int]) -> int: """ Returns the subarray with maximum sum - >>> maxSubArray([1,2,3,4,-2]) + >>> max_subarray([1,2,3,4,-2]) 10 - >>> maxSubArray([-2,1,-3,4,-1,2,1,-5,4]) + >>> max_subarray([-2,1,-3,4,-1,2,1,-5,4]) 6 """ @@ -23,4 +23,4 @@ def maxSubArray(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(maxSubArray(array)) + print(max_subarray(array))