Skip to content

Largest-sum run of consecutive elements

Question

Given an array of positive and negative numbers, find the contiguous block of elements whose sum is as large as possible.

Short answer

Kadane's algorithm: one pass, O(n)O(n) time, O(1)O(1) space. Track the best sum of a block ending at the current element, bi=max⁡(ai, bi−1+ai)b_i=\max(a_i,\,b_{i-1}+a_i), and the best value of bib_i seen so far, recording start and end indices when it improves. A negative running sum can never help later, so the block restarts there; if all entries are negative the answer is the largest single element.

Adapted from Zhou, A Practical Guide to Quantitative Finance Interviews, sec. 7.1 Algorithms, 'Maximum contiguous subarray', p.180; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question