Complexity and efficiency · 13 / 15 Exercise Hard

Maximum subarray

Objective

Create a Python program that finds the largest sum of consecutive elements of a list, and compares an O(n²) brute-force solution with Kadane's algorithm, which solves it in O(n).

Instructions

  • Read a line with integers (positive and negative) separated by spaces. The list has at least one element.
  • Brute force: for each starting position i, add going right with j = i..n-1 and count one step for each sum computed.
  • Kadane: start with current and best equal to the first value, with 1 step. For each following value v do current = max(v, current + v) and best = max(best, current), and count one step.
  • Show Maximum sum: s (Kadane's result), Brute force steps: x and Kadane steps: y.
Input
-2 1 -3 4 -1 2 1 -5 4
Output
Maximum sum: 6
Brute force steps: 45
Kadane steps: 9

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise