Skip to content

Added kadane_algo.py #12228

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions data_structures/arrays/kadane_algo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# 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

Check failure on line 15 in data_structures/arrays/kadane_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (PLR1730)

data_structures/arrays/kadane_algo.py:14:9: PLR1730 Replace `if` statement with `max_global = max(max_current, max_global)`

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)
Loading