📖 Scenario: You are analyzing daily temperature changes represented as an array of integers. You want to find the period with the highest total increase in temperature.
🎯 Goal: Build a C++ program that uses the divide and conquer method to find the maximum sum of a contiguous subarray (maximum subarray) in the given array.
📋 What You'll Learn
Create an integer array called arr with the exact values: {-2, 1, -3, 4, -1, 2, 1, -5, 4}
Create an integer variable called n that stores the size of arr
Write a function maxCrossingSum that finds the maximum subarray sum crossing the middle index
Write a recursive function maxSubArraySum that uses divide and conquer to find the maximum subarray sum
Print the maximum subarray sum found by maxSubArraySum
💡 Why This Matters
🌍 Real World
Finding maximum subarrays is useful in financial analysis to find the best time to buy and sell stocks, or in signal processing to detect strong signals.
💼 Career
Understanding divide and conquer algorithms and recursion is important for software engineering roles that require problem solving and optimization skills.
Progress0 / 4 steps
1
Create the array and its size
Create an integer array called arr with the exact values {-2, 1, -3, 4, -1, 2, 1, -5, 4}. Then create an integer variable called n that stores the size arr.
DSA C++
Hint
Use int arr[] = {...}; to create the array and int n = sizeof(arr) / sizeof(arr[0]); to get its size.
2
Write the maxCrossingSum function
Write a function called maxCrossingSum that takes the array arr, integers left, mid, and right as parameters. It should find the maximum sum of a subarray crossing the middle index mid.
DSA C++
Hint
Use two loops: one going left from mid to left, and one going right from mid+1 to right. Track max sums on both sides and return their sum.
3
Write the maxSubArraySum recursive function
Write a recursive function called maxSubArraySum that takes the array arr, integers left and right as parameters. It should use divide and conquer to find the maximum subarray sum between left and right.
DSA C++
Hint
Use recursion to find max subarray sum in left half, right half, and crossing mid. Return the maximum of these three.
4
Print the maximum subarray sum
In the main function, call maxSubArraySum with arr, 0, and n - 1 as arguments. Print the returned maximum subarray sum using cout.
DSA C++
Hint
Call maxSubArraySum(arr, 0, n - 1) and print the result using cout.
Practice
(1/5)
1. What is the main idea behind the Divide and Conquer approach to find the maximum subarray sum?
easy
A. Use a sliding window to find the max sum subarray in one pass
B. Sort the array and pick the largest element as max subarray sum
C. Divide the array into two halves, find max subarray in left, right, and crossing middle, then combine results
D. Calculate all possible subarrays and pick the one with max 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 subarrays crossing the middle, then take the maximum.
Final Answer:
Divide the array into two halves, find max subarray in left, right, and crossing middle, then combine results -> Option C
Quick Check:
Divide and conquer = split and combine max sums [OK]
Hint: Split array, check left, right, and crossing sums [OK]
Common Mistakes:
Thinking sorting helps find max subarray sum
Ignoring subarrays crossing the middle
Trying to check all subarrays without divide and conquer
2. Which of the following is the correct base case condition in the divide and conquer function for maximum subarray?
easy
A. if (low >= high) return arr[low] + arr[high];
B. if (low > high) return 0;
C. if (low == high) return 0;
D. if (low == high) return arr[low];
Solution
Step 1: Identify base case for single element
When low equals high, the subarray has one element, so max sum is that element itself.
Step 2: Check options for correct base case
if (low == high) return arr[low]; returns arr[low] when low == high, which is correct base case.
Final Answer:
if (low == high) return arr[low]; -> Option D
Quick Check:
Single element subarray max sum = element value [OK]
Hint: Base case: single element returns that element [OK]
Common Mistakes:
Returning 0 for single element subarray
Using incorrect comparison operators in base case
Returning sum of two elements when only one element left
3. What is the output of the following code snippet using divide and conquer to find max subarray sum?
int arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int n = 9;
int maxCrossingSum(int arr[], int low, int mid, int high) {
int sum = 0, left_sum = INT_MIN;
for (int i = mid; i >= low; i--) {
sum += arr[i];
if (sum > left_sum) left_sum = sum;
}
sum = 0; int right_sum = INT_MIN;
for (int i = mid + 1; i <= high; i++) {
sum += arr[i];
if (sum > right_sum) right_sum = sum;
}
return left_sum + right_sum;
}
int maxSubArraySum(int arr[], int low, int high) {
if (low == high) return arr[low];
int mid = (low + high) / 2;
int left_max = maxSubArraySum(arr, low, mid);
int right_max = maxSubArraySum(arr, mid + 1, high);
int cross_max = maxCrossingSum(arr, low, mid, high);
return max(max(left_max, right_max), cross_max);
}
int result = maxSubArraySum(arr, 0, n - 1);
std::cout << result;
medium
A. 6
B. 7
C. 5
D. 4
Solution
Step 1: Identify the maximum subarray
The array is [-2, 1, -3, 4, -1, 2, 1, -5, 4]. The subarray [4, -1, 2, 1] (indices 3-6) sums to 6, the maximum.
Hint: Check sums of subarrays crossing middle carefully [OK]
Common Mistakes:
Confusing max crossing sum with max overall sum
Miscounting indices in loops
Assuming max sum includes all positive numbers only
4. Identify the bug in this divide and conquer max subarray code snippet:
int maxCrossingSum(int arr[], int low, int mid, int high) {
int sum = 0, left_sum = 0;
for (int i = mid; i >= low; i--) {
sum += arr[i];
if (sum > left_sum) left_sum = sum;
}
sum = 0; int right_sum = 0;
for (int i = mid + 1; i <= high; i++) {
sum += arr[i];
if (sum > right_sum) right_sum = sum;
}
return left_sum + right_sum;
}
medium
A. left_sum and right_sum should be initialized to INT_MIN, not 0
B. The loops should run from low to mid and mid+1 to high respectively
C. sum should not be reset to 0 before right loop
D. The function should return max(left_sum, right_sum) instead of sum
Solution
Step 1: Check initialization of left_sum and right_sum
They are initialized to 0, which fails if all numbers are negative because max sum could be less than 0.
Step 2: Correct initialization to INT_MIN
Initializing left_sum and right_sum to INT_MIN ensures negative sums are correctly handled.
Final Answer:
left_sum and right_sum should be initialized to INT_MIN, not 0 -> Option A
Quick Check:
Initialize max sums to INT_MIN to handle negatives [OK]
Hint: Use INT_MIN for max sums to handle negative values [OK]
Common Mistakes:
Initializing max sums to zero causing wrong results
Incorrect loop directions
Not resetting sum before right loop
5. Given an array arr = [-1, -2, -3, -4], what will the divide and conquer maximum subarray function return?
hard
A. -10
B. -1
C. 0
D. -4
Solution
Step 1: Understand max subarray with all negative numbers
When all numbers are negative, max subarray is the single largest element (least negative).
Step 2: Find largest element in arr
Elements are -1, -2, -3, -4. The largest is -1.
Final Answer:
-1 -> Option B
Quick Check:
Max subarray in negatives = max element [OK]
Hint: Max subarray in all negatives is max single element [OK]
Common Mistakes:
Returning sum of all elements instead of max single element
Returning zero incorrectly assuming empty subarray
Ignoring negative values in max calculation
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.