Skip to content

Commit 98b1ebc

Browse files
author
Amogh Singhal
authored
Create maximum_subarray_sum.py
1 parent 663f7b4 commit 98b1ebc

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

maximum_subarray_sum.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Problem: Given a list of positive and negative numbers, find the maximum subarray sum.
2+
# Constraint: Solve it in O(n)
3+
4+
# Solution: Use two variables to hold sums
5+
# a. overall sum -- initialize to first element
6+
# b. partial sum -- initialize to first element
7+
# Traverse over the whole array
8+
# If the current element is greater than partial sum, swap the partial sum with the current element
9+
# If the partial sum is greater than overall sum, swap overall with partial sum
10+
# the overall sum will be the contiguous subarray with the largest sum
11+
12+
def maxSubArraySum(arr):
13+
max_so_far = arr[0]
14+
current_max = arr[0]
15+
16+
for i in range(1,len(arr)):
17+
current_max = max(arr[i], current_max + arr[i])
18+
max_so_far = max(max_so_far, current_max)
19+
20+
return max_so_far
21+
22+
sampleArr = [-2, -3, 4, -1, -2, 1, 5, -3]
23+
24+
solution = maxSubArraySum(sampleArr)
25+
print(solution)

0 commit comments

Comments
 (0)