Data Structures & Algorithms

Table of Contents

Max subarray

Problem

Assume array of integers. Give maximum sum of elements of a contiguous subarray.

A = [-6, 2, -4, 1, 3, -1, 5, -1]

Solution Create a table containing arrays A and a new array B. Initialise first element of B with max(A[1], 0):

A-62-413-151
B0

For each cell B:

A-62-413-15-1
B02014387

m holds the highest sum: m=8

To find subarray, go back from m until you find a 0. [1,3,-1,5]

Complexity The brute force algorithm is is in O(n2) Divide and conquer is in O(nlogn) DP brings it down to O(n).

$S(i) = \begin{cases} A[i] & \text{if } i = 0\\ \max {S(i-1)+A[i], A[i]} & otherwise \end{cases}$