Case study: Maximum Subarray

Example

Given the subarray has sum . It is the best we can do.

Convention. We can take , so , and the sume is zero.

Brute force algorithm

Runtime:

Improved brute force algorithm Idea: we recompute the same sum many times in the loop.

Runtime:

But we can do better. Let’s introduce the concept of Divide and Conquer

Idea: solve the problem twice in size (we assume is a power of 2). Then the optimal subarray (if not empty)

  1. is completely in the left half
  2. or is completely in the right half
  3. or contains both and (cases mutually exclusive)