Algorithm Steps
- Given an integer array
arr
. - Initialize two variables:
max_sum
andcurrent_sum
with the value of the first element. - Iterate through the array starting from index 1.
- At each step, update
current_sum
as the maximum of the current element orcurrent_sum + current_element
. - Update
max_sum
ifcurrent_sum
is greater thanmax_sum
. - After the loop, return
max_sum
as the result.
Find Maximum Subarray Sum using Kadane's Algorithm Code
Python
JavaScript
Java
C++
C
def max_subarray_sum(arr):
max_sum = current_sum = arr[0]
for num in arr[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
# Sample Input
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print("Maximum Subarray Sum:", max_subarray_sum(arr))