From f975ade4d2d844ab4509a1347c5bb63051dc2421 Mon Sep 17 00:00:00 2001 From: rogerdemello Date: Mon, 7 Oct 2024 06:57:26 +0530 Subject: [PATCH 1/2] Kadane's Algorithm --- data_structures/arrays/KadaneAlgo.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 data_structures/arrays/KadaneAlgo.py diff --git a/data_structures/arrays/KadaneAlgo.py b/data_structures/arrays/KadaneAlgo.py new file mode 100644 index 000000000000..2658a0e28ab9 --- /dev/null +++ b/data_structures/arrays/KadaneAlgo.py @@ -0,0 +1,18 @@ +def maximumSubarraySum(arr): + n = len(arr) + maxSum = -1e8 + currSum = 0 + + for i in range(0, n): + currSum = currSum + arr[i] + if(currSum > maxSum): + maxSum = currSum + if(currSum < 0): + currSum = 0 + + return maxSum + +if __name__ == "__main__": + # Your code goes here + arr = [1, 2, -54, 34, 22, 55, -22] #input your array here + print(maximumSubarraySum(arr)) \ No newline at end of file From b0550c99cb69e2be7aa02e5998d5f5e5e9418329 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 7 Oct 2024 01:52:48 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- data_structures/arrays/KadaneAlgo.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/data_structures/arrays/KadaneAlgo.py b/data_structures/arrays/KadaneAlgo.py index 2658a0e28ab9..db094af3c160 100644 --- a/data_structures/arrays/KadaneAlgo.py +++ b/data_structures/arrays/KadaneAlgo.py @@ -1,18 +1,19 @@ def maximumSubarraySum(arr): - n = len(arr) - maxSum = -1e8 - currSum = 0 + n = len(arr) + maxSum = -1e8 + currSum = 0 + + for i in range(0, n): + currSum = currSum + arr[i] + if currSum > maxSum: + maxSum = currSum + if currSum < 0: + currSum = 0 + + return maxSum - for i in range(0, n): - currSum = currSum + arr[i] - if(currSum > maxSum): - maxSum = currSum - if(currSum < 0): - currSum = 0 - - return maxSum if __name__ == "__main__": # Your code goes here - arr = [1, 2, -54, 34, 22, 55, -22] #input your array here - print(maximumSubarraySum(arr)) \ No newline at end of file + arr = [1, 2, -54, 34, 22, 55, -22] # input your array here + print(maximumSubarraySum(arr))