PROBLEM STATEMENT:
The Maximum Subarray Problem is to find the contiguous subarray within a one-dimensional
array of numbers (both positive and negative) that has the largest sum. Given an array A of n
integers, find indices i and j such that the sum of elements A[i] + A[i+1] + ... + A[j] is
maximized, where 0 ≤ i ≤ j < n.
DIVIDE AND CONQUER APPROACH BASED SOLUTION:
The Divide and Conquer approach splits the array into two halves recursively and then
combines the results to find the maximum subarray. The solution involves three possible cases:
1. The maximum subarray lies entirely in the left half.
2. The maximum subarray lies entirely in the right half.
3. The maximum subarray crosses the middle of the array.
To solve the problem, we recursively find the maximum subarray in the left and right halves,
and then compute the maximum subarray that crosses the midpoint. The final result is the
maximum of these three values.
PSEUDOCODE
function maxCrossingSum(arr, l, m, h)
# Include elements on left of mid.
sm = 0
left_sum = -10000
for i =m to l
sm = sm + arr[i]
if (sm > left_sum):
left_sum = sm
# Include elements on right of mid
sm = 0
right_sum = -10000
for i =m to h
sm = sm + arr[i]
if (sm > right_sum):
right_sum = sm
return max(left_sum + right_sum - arr[m], left_sum, right_sum)
function maxSubArraySum(arr, l, h):
if (l > h)
return -10000
if (l == h)
return arr[l]
m = (l + h) // 2
return max(maxSubArraySum(arr, l, m-1),
maxSubArraySum(arr, m+1, h),
maxCrossingSum(arr, l, m, h))
PROBLEM 1
TIME COMPLEXITY
O(n log n) because we recursively split the array into halves (log n levels), and at each level,
combining the results takes linear time (O(n)).