Find Maximum Subarray Divide and Conquer in DSA Java - Time & Space Complexity
We want to understand how the time needed to find the maximum subarray grows as the input array gets bigger.
Specifically, we ask: How does the divide and conquer method scale with input size?
Analyze the time complexity of the following code snippet.
public int maxSubArray(int[] nums, int left, int right) {
if (left == right) return nums[left];
int mid = (left + right) / 2;
int leftMax = maxSubArray(nums, left, mid);
int rightMax = maxSubArray(nums, mid + 1, right);
int crossMax = maxCrossingSubArray(nums, left, mid, right);
return Math.max(Math.max(leftMax, rightMax), crossMax);
}
private int maxCrossingSubArray(int[] nums, int left, int mid, int right) {
int leftSum = Integer.MIN_VALUE, sum = 0;
for (int i = mid; i >= left; i--) {
sum += nums[i];
if (sum > leftSum) leftSum = sum;
}
int rightSum = Integer.MIN_VALUE;
sum = 0;
for (int i = mid + 1; i <= right; i++) {
sum += nums[i];
if (sum > rightSum) rightSum = sum;
}
return leftSum + rightSum;
}
This code finds the maximum sum of a contiguous subarray using divide and conquer.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls splitting the array into halves.
- How many times: Each call splits the array until single elements remain, about log n levels.
- Additional operation: The maxCrossingSubArray scans parts of the array linearly at each level.
- Dominant operation: The linear scans in maxCrossingSubArray at each recursion level.
At each level, the array is split into two halves, and the crossing sum is found by scanning parts of the array.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 + 5 + 5 + ... ≈ 30 operations |
| 100 | About 100 + 50 + 50 + ... ≈ 700 operations |
| 1000 | About 1000 + 500 + 500 + ... ≈ 9000 operations |
Pattern observation: The total work roughly doubles with each doubling of input size, growing a bit faster than linear but less than quadratic.
Time Complexity: O(n log n)
This means the time grows a bit faster than the size of the input, multiplying by the logarithm of the input size.
[X] Wrong: "Since the array is split in half each time, the time complexity must be O(log n)."
[OK] Correct: Although the array splits reduce the problem size, the crossing sum requires scanning parts of the array at each level, adding linear work per level, so total time is O(n log n), not just O(log n).
Understanding this divide and conquer approach helps you see how breaking problems down and combining results affects performance, a key skill in many coding challenges.
"What if we replaced the linear scan in maxCrossingSubArray with a constant-time operation? How would the time complexity change?"
Practice
Divide and Conquer approach to find the maximum subarray sum?Solution
Step 1: Understand divide and conquer strategy
The array is divided into two halves recursively to simplify the problem.Step 2: Combine results from left, right, and crossing subarrays
We find max subarray sums in left half, right half, and subarrays crossing the middle, then take the maximum.Final Answer:
Split array, find max in left, right, crossing, then combine -> Option CQuick Check:
Divide and conquer = split and combine max sums [OK]
- Thinking sorting helps find max subarray sum
- Confusing divide and conquer with sliding window
- Ignoring subarrays crossing the middle
Solution
Step 1: Identify base case for recursion
The recursion stops when the subarray has only one element.Step 2: Return the single element as max subarray sum
Since one element is the smallest subarray, return it directly.Final Answer:
Return single element when array size is one -> Option BQuick Check:
Base case = single element return [OK]
- Returning 0 for empty array instead of handling single element
- Using sum of two elements as base case
- Not defining a base case causing infinite recursion
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println(maxSubArray(arr, 0, arr.length - 1));
// Assume maxSubArray is correctly implemented divide and conquer methodSolution
Step 1: Identify max subarray in given array
The max subarray is [4, -1, 2, 1] with sum 4 + (-1) + 2 + 1 = 6.Step 2: Check if any larger sum exists
Adding the next element -5 or 4 does not increase sum beyond 6, but including the last 4 gives total 5 for subarray [4, -1, 2, 1, -5, 4]?Step 3: Correct max subarray is [4, -1, 2, 1] with sum 6
Actually, the max sum is 6, not 5.Final Answer:
6 -> Option DQuick Check:
Max subarray sum = 6 [OK]
- Choosing sum including negative elements that reduce total
- Miscounting elements in max subarray
- Confusing max sum with max element
int maxCrossingSum(int[] arr, int left, int mid, int right) {
int sum = 0, left_sum = Integer.MIN_VALUE;
for (int i = mid; i >= left; i--) {
sum += arr[i];
if (sum > left_sum) left_sum = sum;
}
sum = 0;
int right_sum = Integer.MIN_VALUE;
for (int i = mid + 1; i <= right; i++) {
sum += arr[i];
if (sum > right_sum) right_sum = sum;
}
return left_sum + right_sum;
}Solution
Step 1: Analyze loops for left and right sums
Loops correctly accumulate sums from mid to left and mid+1 to right.Step 2: Check return statement
Returns sum of max left and right sums crossing mid, which is correct for crossing subarray.Final Answer:
No error, code correctly finds max crossing sum -> Option AQuick Check:
Crossing sum = left max + right max [OK]
- Initializing sum to wrong value causing incorrect sums
- Returning max instead of sum of left and right max
- Incorrect loop boundaries skipping elements
int[] arr = {-1, -2, -3, -4}, what will the divide and conquer algorithm return as the maximum subarray sum?Solution
Step 1: Understand max subarray with all negative numbers
When all numbers are negative, max subarray is the single largest (least negative) element.Step 2: Identify largest element in array
Largest element is -1, so max subarray sum is -1.Final Answer:
-1 -> Option AQuick Check:
Max subarray sum with negatives = max element [OK]
- Summing all negatives instead of picking max element
- Returning zero incorrectly assuming empty subarray
- Confusing max subarray sum with min element
Ready to prove it?
Pass the test and this pattern moves unknown
