Skip to content

Commit 4968dd6

Browse files
Create longest_sum_contigous_array.py
1 parent 162024f commit 4968dd6

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
"""
2+
Find the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum.
3+
4+
The idea of algorithm is to look for all positive contiguous segments of the array (max_ending_here is used for this).
5+
And keep track of maximum sum contiguous segment among all positive segments (max_so_far is used for this).
6+
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
7+
8+
Example)
9+
Let input array = [-2,-3,4,-1,-2,1,5,3]
10+
11+
max_so_far = max_ending_here = 0
12+
13+
for i=0, a[0] = -2
14+
max_ending_here = max_ending_here + (-2)
15+
Set max_ending_here = 0 because max_ending_here < 0
16+
17+
for i=1, a[1] = -3
18+
max_ending_here = max_ending_here + (-3)
19+
Set max_ending_here = 0 because max_ending_here < 0
20+
21+
for i=2, a[2] = 4
22+
max_ending_here = max_ending_here + (4)
23+
max_ending_here = 4
24+
max_so_far is updated to 4 because max_ending_here greater
25+
than max_so_far which was 0 till now
26+
27+
for i=3, a[3] = -1
28+
max_ending_here = max_ending_here + (-1)
29+
max_ending_here = 3
30+
31+
for i=4, a[4] = -2
32+
max_ending_here = max_ending_here + (-2)
33+
max_ending_here = 1
34+
35+
for i=5, a[5] = 1
36+
max_ending_here = max_ending_here + (1)
37+
max_ending_here = 2
38+
39+
for i=6, a[6] = 5
40+
max_ending_here = max_ending_here + (5)
41+
max_ending_here = 7
42+
max_so_far is updated to 7 because max_ending_here is
43+
greater than max_so_far
44+
45+
for i=7, a[7] = -3
46+
max_ending_here = max_ending_here + (-3)
47+
max_ending_here = 4
48+
49+
4+(-1)+(-2)+1+5 = 7
50+
hence,maximum contiguous array sum is 7
51+
"""
52+
def max_subarray_sum(a,size):
53+
54+
max_so_far = 0
55+
max_ending_here = 0
56+
57+
for i in range(0, size):
58+
max_ending_here = max_ending_here + a[i]
59+
if max_ending_here < 0:
60+
max_ending_here = 0
61+
elif (max_so_far < max_ending_here):
62+
max_so_far = max_ending_here
63+
64+
return max_so_far

0 commit comments

Comments
 (0)