Maximum Subarray

Problem Statement

deeksha sharma
Algorithm Problems
2 min readOct 12, 2015

--

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.

Approach

1)If all integers are negative, then return the greatest number from the array.

2)If all integers are positive, then return the sum of all integers in the array.

3)If integers are positive and negative both then:
Initialize variables : maximumSum(keeps track of the maximum sum so far) and currentSum(keeps adding every element in the array) = 0.

4)While going through each Integer in the array if currentSum ⇐ 0, then set the value of currentSum = 0 and check if maximumSum < currentSum, then maximumSum = currentSum.

5)maximumSum will be the largest sum.

Runtime Complexity

Worst case runtime complexity is O(n) since maximum sum is found by going through the array in 1 pass.

--

--

deeksha sharma
Algorithm Problems

Work for https://bonsaiilabs.com/ life long learner ,investing time heavily in personal finance, education, tech and design skills. Twitter: @deekshasharma25