From 8a3367be1ed4df8926c30faa946e25b57f72ee28 Mon Sep 17 00:00:00 2001 From: Vibhanshu Singh <135852806+singhvibhanshu@users.noreply.github.com> Date: Mon, 21 Oct 2024 22:08:35 +0530 Subject: [PATCH 1/2] Create kadane_algo.py fixes #12224 --- data_structures/arrays/kadane_algo.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 data_structures/arrays/kadane_algo.py diff --git a/data_structures/arrays/kadane_algo.py b/data_structures/arrays/kadane_algo.py new file mode 100644 index 000000000000..2ccc6b531421 --- /dev/null +++ b/data_structures/arrays/kadane_algo.py @@ -0,0 +1,22 @@ +# Function to find the maximum sum of a subarray +def kadanes_algorithm(arr): + # Initializing variables + max_current = arr[0] # This will store the current max sum + max_global = arr[0] # This will store the global max sum + + # Loop through the array starting from the second element + for i in range(1, len(arr)): + # Update the current max sum by choosing the maximum between + # the current element alone or the current element plus the previous max + max_current = max(arr[i], max_current + arr[i]) + + # Update the global max sum if the current max is larger + if max_current > max_global: + max_global = max_current + + return max_global + +# Example usage +arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4] +result = kadanes_algorithm(arr) +print("Maximum subarray sum is:", result) From e0462f0b5001618740c937b16509949468c31abf Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 21 Oct 2024 16:40:04 +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/kadane_algo.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/data_structures/arrays/kadane_algo.py b/data_structures/arrays/kadane_algo.py index 2ccc6b531421..474e3c509875 100644 --- a/data_structures/arrays/kadane_algo.py +++ b/data_structures/arrays/kadane_algo.py @@ -2,7 +2,7 @@ def kadanes_algorithm(arr): # Initializing variables max_current = arr[0] # This will store the current max sum - max_global = arr[0] # This will store the global max sum + max_global = arr[0] # This will store the global max sum # Loop through the array starting from the second element for i in range(1, len(arr)): @@ -16,6 +16,7 @@ def kadanes_algorithm(arr): return max_global + # Example usage arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4] result = kadanes_algorithm(arr)