Skip to content

Commit df6fcc4

Browse files
authored
Merge pull request #258 from master-fury/master
Added Kadane Algorithm
2 parents a6a143b + 1e5e9bc commit df6fcc4

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Kadane's Algorithm by Master-Fury
2+
# Worst and Average Case Time Complexity: O(n)
3+
4+
from sys import maxsize # importing maximum int from sys module
5+
6+
7+
def kadane_algorithm(arr: int):
8+
9+
len_arr = len(arr) # Finding the len of array
10+
11+
max_so_far = -maxsize - 1 # Setting max value as maximum negative value
12+
max_ending_here = 0
13+
14+
for i in range(0, len_arr):
15+
max_ending_here = max_ending_here + arr[i]
16+
if (max_so_far < max_ending_here):
17+
max_so_far = max_ending_here
18+
19+
if max_ending_here < 0:
20+
max_ending_here = 0
21+
22+
return max_so_far
23+
24+
25+
# Driver function
26+
sample_array = [-5, -2, 5, 9, -8, 9, 4, 7, -7, -1]
27+
max_cont_subarray_sum = kadane_algorithm(sample_array)
28+
29+
print("The maximum sum of contigous sub array is - ", max_cont_subarray_sum)
30+
31+
# DESCRIPTION
32+
# This algorithm is widely used to find the sum of contiguous subarray within a one-dimensional array of numbers that has the largest sum.
33+
# The simple idea of Kadane’s algorithm is to look for all positive contiguous segments of the array (max_ending_here is used for this).
34+
# And keep track of maximum sum contiguous segment among all positive segments (max_so_far is used for this).
35+
# Each time we get a positive-sum compare it with max_so_far and update max_so_far if it is greater than max_so_far .
36+
# It can be viewed both as a greedy and DP problem.

0 commit comments

Comments
 (0)