Bird
Raised Fist0
DSA Goprogramming

Find Maximum Subarray Divide and Conquer in DSA Go

Choose your learning style10 modes available
Mental Model
Split the array into halves, find the best subarray in left, right, and crossing the middle, then pick the best.
Analogy: Imagine cutting a chocolate bar into two pieces, finding the tastiest part in each piece and also the tastiest part crossing the cut, then choosing the best overall.
Array: [ -2, 1, -3, 4, -1, 2, 1, -5, 4 ]
Split: [ -2, 1, -3, 4, -1 ] | [ 2, 1, -5, 4 ]
Middle: index 4
Left max subarray -> Right max subarray -> Cross max subarray
Dry Run Walkthrough
Input: array: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Goal: Find the maximum sum of any contiguous subarray using divide and conquer
Step 1: Split array into left [-2,1,-3,4,-1] and right [2,1,-5,4]
Left: [-2,1,-3,4,-1] | Right: [2,1,-5,4]
Why: Divide problem into smaller parts to solve recursively
Step 2: Find max subarray in left half recursively
Left max subarray: [4, -1, 2, 1] with sum 6
Why: Find best subarray in left half
Step 3: Find max subarray in right half recursively
Right max subarray: [4] with sum 4
Why: Find best subarray in right half
Step 4: Find max crossing subarray crossing middle index 4
Cross max subarray: [4, -1, 2, 1] with sum 6
Why: Check subarrays crossing the middle for max sum
Step 5: Compare left max (6), right max (4), and cross max (6), choose max
Max subarray: [4, -1, 2, 1] with sum 6
Why: Final answer is the maximum among the three
Result:
4 -> -1 -> 2 -> 1 -> null with sum 6
Annotated Code
DSA Go
package main

import "fmt"

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

func maxCrossingSum(arr []int, left, mid, right int) (int, int, int) {
    leftSum := -1 << 31
    sum := 0
    maxLeft := mid
    for i := mid; i >= left; i-- {
        sum += arr[i]
        if sum > leftSum {
            leftSum = sum
            maxLeft = i
        }
    }

    rightSum := -1 << 31
    sum = 0
    maxRight := mid + 1
    for j := mid + 1; j <= right; j++ {
        sum += arr[j]
        if sum > rightSum {
            rightSum = sum
            maxRight = j
        }
    }

    return maxLeft, maxRight, leftSum + rightSum
}

func maxSubArraySum(arr []int, left, right int) (int, int, int) {
    if left == right {
        return left, right, arr[left]
    }

    mid := (left + right) / 2

    leftLow, leftHigh, leftSum := maxSubArraySum(arr, left, mid)
    rightLow, rightHigh, rightSum := maxSubArraySum(arr, mid+1, right)
    crossLow, crossHigh, crossSum := maxCrossingSum(arr, left, mid, right)

    if leftSum >= rightSum && leftSum >= crossSum {
        return leftLow, leftHigh, leftSum
    } else if rightSum >= leftSum && rightSum >= crossSum {
        return rightLow, rightHigh, rightSum
    } else {
        return crossLow, crossHigh, crossSum
    }
}

func main() {
    arr := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4}
    low, high, sum := maxSubArraySum(arr, 0, len(arr)-1)
    fmt.Printf("Maximum subarray: ")
    for i := low; i <= high; i++ {
        fmt.Printf("%d", arr[i])
        if i < high {
            fmt.Printf(" -> ")
        }
    }
    fmt.Printf(" -> null with sum %d\n", sum)
}
mid := (left + right) / 2
Find middle index to split array
leftLow, leftHigh, leftSum := maxSubArraySum(arr, left, mid)
Recursively find max subarray in left half
rightLow, rightHigh, rightSum := maxSubArraySum(arr, mid+1, right)
Recursively find max subarray in right half
crossLow, crossHigh, crossSum := maxCrossingSum(arr, left, mid, right)
Find max subarray crossing the middle
if leftSum >= rightSum && leftSum >= crossSum { return leftLow, leftHigh, leftSum } else if rightSum >= leftSum && rightSum >= crossSum { return rightLow, rightHigh, rightSum } else { return crossLow, crossHigh, crossSum }
Return the max among left, right, and crossing subarrays
for i := mid; i >= left; i-- { sum += arr[i]; if sum > leftSum { leftSum = sum; maxLeft = i } }
Find max sum subarray ending at mid from left side
for j := mid + 1; j <= right; j++ { sum += arr[j]; if sum > rightSum { rightSum = sum; maxRight = j } }
Find max sum subarray starting at mid+1 from right side
OutputSuccess
Maximum subarray: 4 -> -1 -> 2 -> 1 -> null with sum 6
Complexity Analysis
Time: O(n log n) because the array is split into halves recursively and each merge step takes O(n) to find crossing sum
Space: O(log n) due to recursion stack depth proportional to log n
vs Alternative: Better than naive O(n^2) approach which checks all subarrays; slower than Kadane's O(n) but uses divide and conquer strategy
Edge Cases
empty array
function does not run because input size is zero; no subarray to find
DSA Go
if left == right { return left, right, arr[left] }
single element array
returns that element as max subarray
DSA Go
if left == right { return left, right, arr[left] }
all negative numbers
returns the least negative number as max subarray
DSA Go
initial leftSum and rightSum set to very small number to handle negatives
When to Use This Pattern
When you see a problem asking for maximum sum subarray and want a divide and conquer approach, use this pattern to split and combine results efficiently.
Common Mistakes
Mistake: Not correctly handling the crossing subarray sums leading to wrong max subarray
Fix: Carefully compute max sum subarray crossing the middle by expanding left and right sums separately
Mistake: Using incorrect base case causing infinite recursion or wrong results
Fix: Use base case when left == right to return that single element as max subarray
Summary
Finds the maximum sum contiguous subarray using divide and conquer.
Use when you want a recursive approach splitting the problem into halves.
The key insight is to consider max subarrays in left, right, and crossing the middle and pick the best.

Practice

(1/5)
1. What is the main idea behind the Divide and Conquer approach to find the maximum subarray sum?
easy
A. Split the array into two halves, find max subarray in left, right, and crossing middle, then combine results
B. Sort the array and pick the largest element as max subarray sum
C. Use a sliding window to find the max sum subarray in one pass
D. Calculate sum of all subarrays and pick the maximum

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 subproblems

    Find max subarray in left half, right half, and crossing the middle, then take the maximum of these three.
  3. Final Answer:

    Split array, find max in left, right, crossing middle, combine -> Option A
  4. Quick Check:

    Divide and conquer = split and combine max subarrays [OK]
Hint: Divide array, conquer halves, combine max sums [OK]
Common Mistakes:
  • Thinking sorting helps find max subarray sum
  • Confusing divide and conquer with sliding window
  • Calculating all subarrays sums directly
2. Which of the following Go function signatures correctly represents the divide and conquer function to find maximum subarray sum in an array arr between indices low and high?
easy
A. func maxSubArray(arr []int, low int high int) int
B. func maxSubArray(arr int[], low int, high int) int
C. func maxSubArray(arr []int, low int, high int) (int, int)
D. func maxSubArray(arr []int, low, high int) int

Solution

  1. Step 1: Check Go slice and parameter syntax

    In Go, slices are declared as []int, and multiple parameters of same type can be grouped.
  2. Step 2: Identify correct function signature

    func maxSubArray(arr []int, low, high int) int uses correct slice type and groups low, high as int parameters, returning int sum.
  3. Final Answer:

    func maxSubArray(arr []int, low, high int) int -> Option D
  4. Quick Check:

    Go slice syntax and grouped params = func maxSubArray(arr []int, low, high int) int [OK]
Hint: Use []int for slices and group same-type params [OK]
Common Mistakes:
  • Using int[] instead of []int for slices
  • Returning multiple values when only sum needed
  • Separating same-type parameters unnecessarily
3. What is the output of the following Go code snippet that uses divide and conquer to find maximum subarray sum?
package main
import "fmt"

func maxCrossingSum(arr []int, low, mid, high int) int {
    leftSum := -1 << 31
    sum := 0
    for i := mid; i >= low; i-- {
        sum += arr[i]
        if sum > leftSum {
            leftSum = sum
        }
    }
    rightSum := -1 << 31
    sum = 0
    for j := mid + 1; j <= high; j++ {
        sum += arr[j]
        if sum > rightSum {
            rightSum = sum
        }
    }
    return leftSum + rightSum
}

func maxSubArray(arr []int, low, high int) int {
    if low == high {
        return arr[low]
    }
    mid := (low + high) / 2
    leftMax := maxSubArray(arr, low, mid)
    rightMax := maxSubArray(arr, mid+1, high)
    crossMax := maxCrossingSum(arr, low, mid, high)
    if leftMax >= rightMax && leftMax >= crossMax {
        return leftMax
    } else if rightMax >= leftMax && rightMax >= crossMax {
        return rightMax
    } else {
        return crossMax
    }
}

func main() {
    arr := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4}
    fmt.Println(maxSubArray(arr, 0, len(arr)-1))
}
medium
A. 5
B. 7
C. 6
D. 4

Solution

  1. Step 1: Understand the input array and max subarray

    The array is [-2,1,-3,4,-1,2,1,-5,4]. The max subarray is [4,-1,2,1] with sum 6.
  2. Step 2: Trace divide and conquer calls

    The function recursively finds max in left, right, and crossing middle, correctly returning 6.
  3. Final Answer:

    6 -> Option C
  4. Quick Check:

    Max subarray sum = 6 [OK]
Hint: Max subarray for example array is 6 [OK]
Common Mistakes:
  • Choosing sum including -5 which lowers total
  • Confusing max crossing sum with max overall
  • Miscomputing indices for mid and crossing sums
4. Identify the bug in this Go function for finding max crossing sum and select the fix:
func maxCrossingSum(arr []int, low, mid, high int) int {
    leftSum := 0
    sum := 0
    for i := mid; i >= low; i-- {
        sum += arr[i]
        if sum > leftSum {
            leftSum = sum
        }
    }
    rightSum := 0
    sum = 0
    for j := mid + 1; j <= high; j++ {
        sum += arr[j]
        if sum > rightSum {
            rightSum = sum
        }
    }
    return leftSum + rightSum
}
medium
A. Initialize leftSum and rightSum to very small number (e.g. -1<<31) instead of 0
B. Change loops to run from low to mid and mid+1 to high
C. Return max of leftSum and rightSum instead of sum
D. Add 1 to mid when calculating leftSum loop

Solution

  1. Step 1: Analyze initialization of leftSum and rightSum

    They start at 0, which fails if all numbers are negative, missing correct max sums.
  2. Step 2: Fix initialization to very small number

    Set leftSum and rightSum to -1<<31 (minimum int) to correctly track max sums even if negative.
  3. Final Answer:

    Initialize leftSum and rightSum to very small number (e.g. -1<<31) -> Option A
  4. Quick Check:

    Proper initialization avoids missing negative max sums [OK]
Hint: Initialize max sums to very small number, not zero [OK]
Common Mistakes:
  • Starting max sums at zero causes wrong results with negatives
  • Changing loop directions incorrectly
  • Returning sum instead of combined max sums
5. Given an array arr of integers, how would you modify the divide and conquer approach to also return the start and end indices of the maximum subarray along with its sum?
hard
A. Store indices globally and update them only when crossing sum is calculated
B. Change functions to return a struct with sum, start, and end; update recursive calls to track indices
C. Return only sum and find indices by scanning array after result
D. Use a separate loop after divide and conquer to find indices of max sum

Solution

  1. Step 1: Modify function return types

    Change functions to return a struct containing sum, start index, and end index to track subarray boundaries.
  2. Step 2: Update recursive calls and combine logic

    When combining left, right, and crossing results, also combine their indices accordingly to keep track of max subarray range.
  3. Final Answer:

    Return struct with sum, start, end; update recursive calls to track indices -> Option B
  4. Quick Check:

    Return sum and indices together for full max subarray info [OK]
Hint: Return sum plus indices in struct, update recursively [OK]
Common Mistakes:
  • Using global variables causing bugs in recursion
  • Finding indices after sum calculation separately
  • Ignoring indices in crossing sum 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