Given a finite sequence of real numbers, find a nonempty contiguous block with maximum sum. Its restriction to contiguous blocks distinguishes it from choosing an arbitrary subset. The problem admits a linear-time solution using Kadane's algorithm.
For a segment, store its total sum , maximum possibly-empty prefix sum , maximum possibly-empty suffix sum and maximum possibly-empty internal contiguous sum . Adjacent segment summaries combine byA prefix either stays on the left or includes the whole left segment and a right prefix. A suffix has the symmetric decomposition. An internal segment either stays in one child or crosses the boundary as a left suffix followed by a right prefix. These cases prove the formulas, including empty candidates. Store the corresponding endpoints to recover a winning segment. This constant-size summary gives a linear time divide-and-conquer algorithm for the empty-allowed maximum subarray problem.
For input , let be the largest sum of a nonempty contiguous block ending at . The recurrence relation and is exact: an optimal block either starts at or extends an optimal block ending at . The answer is . Keeping only the current and best value gives linear time complexity and constant extra space complexity.
Articles by others on the same topic
The Maximum Subarray Problem is a classic algorithmic problem that involves finding the contiguous subarray within a one-dimensional array of numbers that has the largest sum. In other words, given an array of integers (which can include both positive and negative numbers), the goal is to identify the subarray (a contiguous segment of the array) that yields the highest possible sum.