Skip to content

Commit 8a3367b

Browse files
Create kadane_algo.py
fixes #12224
1 parent 03a4251 commit 8a3367b

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Function to find the maximum sum of a subarray
2+
def kadanes_algorithm(arr):
3+
# Initializing variables
4+
max_current = arr[0] # This will store the current max sum
5+
max_global = arr[0] # This will store the global max sum
6+
7+
# Loop through the array starting from the second element
8+
for i in range(1, len(arr)):
9+
# Update the current max sum by choosing the maximum between
10+
# the current element alone or the current element plus the previous max
11+
max_current = max(arr[i], max_current + arr[i])
12+
13+
# Update the global max sum if the current max is larger
14+
if max_current > max_global:
15+
max_global = max_current
16+
17+
return max_global
18+
19+
# Example usage
20+
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
21+
result = kadanes_algorithm(arr)
22+
print("Maximum subarray sum is:", result)

0 commit comments

Comments
 (0)