THINK FIRST·CODE LATER

← All labs

Maximum subarray: Θ(n²) versus Kadane's Θ(n)

Problem

Given n integers (some negative), find the largest sum of a contiguous, non-empty block — e.g. the best run of days in a list of daily profits and losses.

Write Kadane computing it twice: by brute force (every start, extending the running sum to every end, counting additions) and with Kadane's algorithm (one pass: the best sum ending at i either extends the best sum ending at i − 1, if that is positive, or starts fresh at i). Print the sum, the first block that achieves it, whether both methods agree, and both operation counts.

For the input

9
-2 1 -3 4 -1 2 1 -5 4

the program prints

Maximum subarray sum: 6
From index 3 to 6 (4 elements)
Brute force agrees: true
Additions: brute force 45, Kadane 9

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d6-5-data-1.txt

9
-2 1 -3 4 -1 2 1 -5 4
What your program must print for d6-5-data-1.txt
Maximum subarray sum: 6
From index 3 to 6 (4 elements)
Brute force agrees: true
Additions: brute force 45, Kadane 9

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d6-5-data-1.txt

Windows PowerShell does not understand <:

Get-Content d6-5-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.