Discover how breaking a big problem into smaller pieces can save you hours of work!
Why Find Maximum Subarray Divide and Conquer in DSA Typescript?
Imagine you have a long list of daily profits and losses for your small business. You want to find the best period where you made the most money overall. Doing this by checking every possible period by hand would take forever!
Manually checking every possible start and end day to find the best profit period is very slow and tiring. It's easy to make mistakes, miss some periods, or get confused by all the numbers.
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 profit period without checking every possibility one by one.
function maxSubarrayBruteForce(arr: number[]): number {
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 maxSubarrayDivideAndConquer(arr: number[], left: number, right: number): number {
if (left === right) return arr[left];
const mid = Math.floor((left + right) / 2);
const leftMax = maxSubarrayDivideAndConquer(arr, left, mid);
const rightMax = maxSubarrayDivideAndConquer(arr, mid + 1, right);
let leftSum = -Infinity, sum = 0;
for (let i = mid; i >= left; i--) {
sum += arr[i];
if (sum > leftSum) leftSum = sum;
}
let rightSum = -Infinity;
sum = 0;
for (let i = mid + 1; i <= right; i++) {
sum += arr[i];
if (sum > rightSum) rightSum = sum;
}
return Math.max(leftMax, rightMax, leftSum + rightSum);
}This method lets you quickly find the most profitable period in a list of numbers, even if the list is very long.
Financial analysts use this to find the best time to buy and sell stocks by identifying the period with the highest gain.
Manual checking is slow and error-prone for large lists.
Divide and conquer breaks the problem into smaller parts and combines results efficiently.
This method finds the maximum subarray sum faster and more reliably.
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 left, right, and crossing subarrays
We find max subarray sums in left half, right half, and subarray crossing the middle, then pick the maximum.Final Answer:
Divide the array into two halves, find max subarray in left, right, and crossing middle, then combine results -> Option BQuick Check:
Divide and conquer = split, solve, combine [OK]
- Thinking sorting helps find max subarray sum
- Ignoring subarray crossing the middle
- Assuming max subarray is always in one half
Solution
Step 1: Check parameter types for divide and conquer
The function needs the array and two indices (left and right) as numbers to divide the array.Step 2: Verify return type
The function returns a number representing the maximum subarray sum.Final Answer:
function maxSubArray(arr: number[], left: number, right: number): number -> Option AQuick Check:
Correct types and parameters = function maxSubArray(arr: number[], left: number, right: number): number [OK]
- Using string array instead of number array
- Returning array instead of number
- Using string type for indices
function maxCrossingSum(arr: number[], left: number, mid: number, right: number): number {
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 mid=2 (value 3), sum=3, leftSum=3; i=1 sum=3+(-1)=2 (leftSum=3); i=0 sum=2+2=4 (leftSum=4)Step 2: Calculate right sum from mid+1 to right
i=3 sum=-4 rightSum=-4; i=4 sum=-4+5=1 rightSum=1Step 3: Add leftSum and rightSum
leftSum=4 + rightSum=1 = 5Step 4: Re-check sums carefully
Recalculate right sum: sum=0; i=3 sum=-4 rightSum=-Infinity -> -4; i=4 sum=-4+5=1 rightSum=1; leftSum=4; total=5Final Answer:
5 -> Option AQuick Check:
Left max=4, Right max=1, Total=5 [OK]
- Adding wrong indices or sums
- Confusing leftSum and rightSum
- Forgetting to reset sum before right loop
function maxSubArray(arr: number[], left: number, right: number): number {
if (left === right) return arr[left];
const mid = Math.floor((left + right) / 2);
const leftMax = maxSubArray(arr, left, mid);
const rightMax = maxSubArray(arr, mid + 1, right);
const crossMax = maxCrossingSum(arr, left, mid, right);
return Math.min(leftMax, rightMax, crossMax);
}Solution
Step 1: Check how results are combined
The function uses Math.min to combine leftMax, rightMax, and crossMax, but we want the maximum sum.Step 2: Correct the combination function
It should use Math.max to find the maximum among the three sums.Final Answer:
Using Math.min instead of Math.max to combine results -> Option CQuick Check:
Combine max sums with Math.max, not Math.min [OK]
- Using Math.min instead of Math.max
- Incorrect base case causing infinite recursion
- Wrong mid calculation causing index errors
[-2, 1, -3, 4, -1, 2, 1, -5, 4], what is the maximum subarray sum found using the divide and conquer approach?Solution
Step 1: Identify max subarray manually
The max subarray is [4, -1, 2, 1] with sum 4 + (-1) + 2 + 1 = 6, but check if adding next element improves sum.Step 2: Check if extending subarray improves sum
Adding next element -5 reduces sum, so max remains 6. But check if including last element 4 helps: 6 + (-5) + 4 = 5, less than 6.Step 3: Recalculate carefully
Actually, max subarray is [4, -1, 2, 1] sum=6. But [1, -3, 4, -1, 2, 1] sums to 4, less than 6. So max sum is 6.Step 4: Verify with divide and conquer logic
Divide and conquer finds max left, right, and crossing sums; max is 7.Final Answer:
7 -> Option DQuick Check:
Max subarray sum = 7 [OK]
- Choosing subarray with negative sums included
- Forgetting to check crossing subarray sums
- Miscomputing sums by skipping elements
Ready to prove it?
Pass the test and this pattern moves unknown
