Bird
Raised Fist0
DSA C++programming~20 mins

Find Maximum Subarray Divide and Conquer in DSA C++ - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Master of Maximum Subarray Divide and Conquer
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Maximum Subarray Sum Using Divide and Conquer
What is the output of the following C++ code that finds the maximum subarray sum using divide and conquer?
DSA C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;

int maxCrossingSum(const vector<int>& arr, int left, int mid, int right) {
    int sum = 0;
    int left_sum = INT_MIN;
    for (int i = mid; i >= left; i--) {
        sum += arr[i];
        if (sum > left_sum) left_sum = sum;
    }
    sum = 0;
    int right_sum = INT_MIN;
    for (int i = mid + 1; i <= right; i++) {
        sum += arr[i];
        if (sum > right_sum) right_sum = sum;
    }
    return left_sum + right_sum;
}

int maxSubArraySum(const vector<int>& arr, int left, int right) {
    if (left == right) return arr[left];
    int mid = (left + right) / 2;
    int left_max = maxSubArraySum(arr, left, mid);
    int right_max = maxSubArraySum(arr, mid + 1, right);
    int cross_max = maxCrossingSum(arr, left, mid, right);
    return max({left_max, right_max, cross_max});
}

int main() {
    vector<int> arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
    cout << maxSubArraySum(arr, 0, arr.size() - 1) << endl;
    return 0;
}
A6
B7
C5
D4
Attempts:
2 left
💡 Hint
Think about the subarray with the largest sum in the array {-2, 1, -3, 4, -1, 2, 1, -5, 4}.
❓ Predict Output
intermediate
2:00remaining
Output of Maximum Subarray Sum for All Negative Numbers
What is the output of the following C++ code when the input array contains all negative numbers?
DSA C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;

int maxCrossingSum(const vector<int>& arr, int left, int mid, int right) {
    int sum = 0;
    int left_sum = INT_MIN;
    for (int i = mid; i >= left; i--) {
        sum += arr[i];
        if (sum > left_sum) left_sum = sum;
    }
    sum = 0;
    int right_sum = INT_MIN;
    for (int i = mid + 1; i <= right; i++) {
        sum += arr[i];
        if (sum > right_sum) right_sum = sum;
    }
    return left_sum + right_sum;
}

int maxSubArraySum(const vector<int>& arr, int left, int right) {
    if (left == right) return arr[left];
    int mid = (left + right) / 2;
    int left_max = maxSubArraySum(arr, left, mid);
    int right_max = maxSubArraySum(arr, mid + 1, right);
    int cross_max = maxCrossingSum(arr, left, mid, right);
    return max({left_max, right_max, cross_max});
}

int main() {
    vector<int> arr = {-8, -3, -6, -2, -5, -4};
    cout << maxSubArraySum(arr, 0, arr.size() - 1) << endl;
    return 0;
}
A-2
B-3
C-8
D0
Attempts:
2 left
💡 Hint
The maximum subarray in all negative numbers is the single largest element.
🔧 Debug
advanced
2:00remaining
Identify the Bug in maxCrossingSum Function
The following maxCrossingSum function is intended to find the maximum sum of a subarray crossing the midpoint. What is the bug in this code?
DSA C++
int maxCrossingSum(const vector<int>& arr, int left, int mid, int right) {
    int sum = 0;
    int left_sum = 0;
    for (int i = mid; i >= left; i--) {
        sum += arr[i];
        if (sum > left_sum) left_sum = sum;
    }
    sum = 0;
    int right_sum = 0;
    for (int i = mid + 1; i <= right; i++) {
        sum += arr[i];
        if (sum > right_sum) right_sum = sum;
    }
    return left_sum + right_sum;
}
AThe loops should run from left to mid and mid+1 to right respectively
Bleft_sum and right_sum should be initialized to INT_MIN instead of 0
CThe function should return max(left_sum, right_sum) instead of their sum
DThe sum variable should be reset only once before both loops
Attempts:
2 left
💡 Hint
Consider what happens if all numbers are negative.
🧠 Conceptual
advanced
1:00remaining
Time Complexity of Divide and Conquer Maximum Subarray
What is the time complexity of the divide and conquer algorithm for finding the maximum subarray sum in an array of size n?
AO(n^2)
BO(n)
CO(n log n)
DO(log n)
Attempts:
2 left
💡 Hint
Consider the recurrence relation T(n) = 2T(n/2) + O(n).
🚀 Application
expert
3:00remaining
Find Maximum Subarray Sum and Its Indices Using Divide and Conquer
Given the following C++ code that finds the maximum subarray sum using divide and conquer, what is the output printed by the program?
DSA C++
#include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>
#include <climits>
using namespace std;

tuple<int, int, int> maxCrossingSum(const vector<int>& arr, int left, int mid, int right) {
    int sum = 0;
    int left_sum = INT_MIN;
    int max_left = mid;
    for (int i = mid; i >= left; i--) {
        sum += arr[i];
        if (sum > left_sum) {
            left_sum = sum;
            max_left = i;
        }
    }
    sum = 0;
    int right_sum = INT_MIN;
    int max_right = mid + 1;
    for (int i = mid + 1; i <= right; i++) {
        sum += arr[i];
        if (sum > right_sum) {
            right_sum = sum;
            max_right = i;
        }
    }
    return make_tuple(left_sum + right_sum, max_left, max_right);
}

tuple<int, int, int> maxSubArraySum(const vector<int>& arr, int left, int right) {
    if (left == right) return make_tuple(arr[left], left, right);
    int mid = (left + right) / 2;
    auto [left_sum, left_start, left_end] = maxSubArraySum(arr, left, mid);
    auto [right_sum, right_start, right_end] = maxSubArraySum(arr, mid + 1, right);
    auto [cross_sum, cross_start, cross_end] = maxCrossingSum(arr, left, mid, right);
    if (left_sum >= right_sum && left_sum >= cross_sum) return make_tuple(left_sum, left_start, left_end);
    else if (right_sum >= left_sum && right_sum >= cross_sum) return make_tuple(right_sum, right_start, right_end);
    else return make_tuple(cross_sum, cross_start, cross_end);
}

int main() {
    vector<int> arr = {13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7};
    auto [max_sum, start_idx, end_idx] = maxSubArraySum(arr, 0, arr.size() - 1);
    cout << "Max sum: " << max_sum << ", Start index: " << start_idx << ", End index: " << end_idx << endl;
    return 0;
}
AMax sum: 39, Start index: 7, End index: 14
BMax sum: 48, Start index: 3, End index: 10
CMax sum: 41, Start index: 0, End index: 3
DMax sum: 43, Start index: 7, End index: 10
Attempts:
2 left
💡 Hint
Trace the subarray with the largest sum and note its start and end indices.

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

  1. Step 1: Understand divide and conquer strategy

    The array is split into two halves recursively to simplify the problem.
  2. 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.
  3. Final Answer:

    Divide the array into two halves, find max subarray in left, right, and crossing middle, then combine results -> Option C
  4. 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

  1. Step 1: Identify base case for single element

    When low equals high, the subarray has one element, so max sum is that element itself.
  2. 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.
  3. Final Answer:

    if (low == high) return arr[low]; -> Option D
  4. 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

  1. 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.
  2. Step 2: Verify code execution

    Top-level split: left_max=4, right_max=4, cross_max=6 (left suffix 4 + right prefix -1+2+1=2). Returns 6.
  3. Final Answer:

    6 -> Option A
  4. Quick Check:

    Max subarray sum = 6 [OK]
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

  1. 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.
  2. Step 2: Correct initialization to INT_MIN

    Initializing left_sum and right_sum to INT_MIN ensures negative sums are correctly handled.
  3. Final Answer:

    left_sum and right_sum should be initialized to INT_MIN, not 0 -> Option A
  4. 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

  1. Step 1: Understand max subarray with all negative numbers

    When all numbers are negative, max subarray is the single largest element (least negative).
  2. Step 2: Find largest element in arr

    Elements are -1, -2, -3, -4. The largest is -1.
  3. Final Answer:

    -1 -> Option B
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard