Discover how breaking a big problem into smaller pieces can save you hours of work!
Why Find Maximum Subarray Divide and Conquer in DSA Javascript?
Imagine you have a long list of daily profits and losses from your small business. You want to find the best continuous period where you made the most money. Doing this by checking every possible period manually would take forever!
Manually checking every possible start and end day means looking at many combinations. This takes a lot of time and is easy to mess up. It's like trying to find the best part of a movie by watching every possible clip one by one.
The divide and conquer method breaks the big problem into smaller parts, solves each part, and then combines the answers. This way, it quickly finds the best continuous period without checking every possibility.
function maxSubarraySum(arr) {
let maxSum = -Infinity;
for (let start = 0; start < arr.length; start++) {
for (let end = start; end < arr.length; end++) {
let sum = 0;
for (let k = start; k <= end; k++) sum += arr[k];
if (sum > maxSum) maxSum = sum;
}
}
return maxSum;
}function maxSubarraySum(arr, left, right) {
if (left === right) return arr[left];
const mid = Math.floor((left + right) / 2);
const leftMax = maxSubarraySum(arr, left, mid);
const rightMax = maxSubarraySum(arr, mid + 1, right);
const crossMax = maxCrossingSum(arr, left, mid, right);
return Math.max(leftMax, rightMax, crossMax);
}This method lets you quickly find the most profitable continuous period in large data sets without wasting time on every possibility.
A stock trader uses this to find the best time window to buy and sell stocks for maximum profit from historical price data.
Manual checking is slow and error-prone for large data.
Divide and conquer splits the problem to solve faster.
It finds the maximum subarray sum efficiently.
Practice
Divide and Conquer approach to find the maximum subarray sum?Solution
Step 1: Understand divide and conquer strategy
The array is split into two halves recursively to simplify the problem.Step 2: Combine results from subproblems
Find max subarray in left half, right half, and crossing the middle, then take the maximum of these three.Final Answer:
Split array, find max left, right, and crossing sums, then combine -> Option AQuick Check:
Divide and conquer = split and combine max sums [OK]
- Thinking sorting helps find max subarray sum
- Ignoring the crossing middle subarray
- Assuming max subarray is always the largest single element
Solution
Step 1: Identify base case for recursion
When the array has only one element, that element itself is the max subarray sum.Step 2: Return the single element value
Return the element value directly as the max sum for that subarray.Final Answer:
Return the single element when array length is 1 -> Option AQuick Check:
Base case single element = element value [OK]
- Returning 0 instead of the element for single element array
- Returning sum of two elements as base case
- Not defining a base case causing infinite recursion
function maxCrossingSum(arr, left, mid, right) {
let sum = 0, leftSum = -Infinity;
for (let i = mid; i >= left; i--) {
sum += arr[i];
if (sum > leftSum) leftSum = sum;
}
sum = 0;
let rightSum = -Infinity;
for (let i = mid + 1; i <= right; i++) {
sum += arr[i];
if (sum > rightSum) rightSum = sum;
}
return leftSum + rightSum;
}
const arr = [2, -1, 3, -4, 5];
console.log(maxCrossingSum(arr, 0, 2, 4));Solution
Step 1: Calculate left sum from mid to left
Starting at index 2 (value 3), sum = 3; then index 1 (-1), sum=2; index 0 (2), sum=4. Max leftSum = 4.Step 2: Calculate right sum from mid+1 to right
Starting at index 3 (-4), sum = -4; index 4 (5), sum=1. Max rightSum = 1.Step 3: Add leftSum and rightSum
4 + 1 = 5.Final Answer:
5 -> Option DQuick Check:
Left max 4 + Right max 1 = 5 [OK]
- Adding wrong subarray sums crossing mid
- Mixing indices for left and right sums
- Using max element instead of max crossing sum
function maxSubArray(arr, left, right) {
if (left === right) return arr[left];
const mid = Math.floor((left + right) / 2);
const leftMax = maxSubArray(arr, left, mid - 1);
const rightMax = maxSubArray(arr, mid + 1, right);
const crossMax = maxCrossingSum(arr, left, mid, right);
return Math.max(leftMax, rightMax, crossMax);
}Solution
Step 1: Check recursive calls range
Left recursive call uses mid - 1, which excludes mid element incorrectly.Step 2: Correct left recursive call to include mid
Change left recursive call to maxSubArray(arr, left, mid) to include mid element.Final Answer:
Left recursive call should be maxSubArray(arr, left, mid) -> Option BQuick Check:
Include mid in left recursion [OK]
- Excluding mid element in recursive calls
- Returning 0 instead of element in base case
- Incorrect mid calculation causing infinite recursion
[-2, 1, -3, 4, -1, 2, 1, -5, 4], what is the maximum subarray sum found using divide and conquer?Solution
Step 1: Identify the max subarray
The subarray [4, -1, 2, 1] (indices 3-6) sums to 4 + (-1) + 2 + 1 = 6.Step 2: Check extending right
[4, -1, 2, 1, -5] = 1 < 6; [4, -1, 2, 1, -5, 4] = 5 < 6.Step 3: Check extending left
[-3, 4, -1, 2, 1] = 3 < 6; further left smaller.Final Answer:
6 -> Option CQuick Check:
Max subarray sum = 6 [OK]
- Miscomputing as 7 by skipping the -3
- Choosing sum 5 by including the end
- Picking single largest element 4
Ready to prove it?
Pass the test and this pattern moves unknown
