THINK FIRST·CODE LATER

← All labs

Maximum subarray by divide and conquer

Problem

Solve the maximum-subarray problem again, now by divide and conquer. The best block of a[low..high] is either entirely in the left half, entirely in the right half, or crosses the middle — and the best crossing block is the best suffix of the left half plus the best prefix of the right half, found in linear time.

Write MaxSubarrayDC with crossing(a, low, mid, high) and the recursive maxSubarray(a, low, high) (mid = (low + high) / 2), counting recursive calls. Print the answer, the number of calls, and the three candidates at the top level.

For the input

8
-2 1 -3 4 -1 2 1 -5

the program prints

Maximum subarray sum: 6
Recursive calls: 15 (2n - 1 = 15)
Top level: left 4, right 3, crossing 6

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.

d7-3-data-1.txt

8
-2 1 -3 4 -1 2 1 -5
What your program must print for d7-3-data-1.txt
Maximum subarray sum: 6
Recursive calls: 15 (2n - 1 = 15)
Top level: left 4, right 3, crossing 6

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 < d7-3-data-1.txt

Windows PowerShell does not understand <:

Get-Content d7-3-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.