1#include <stdio.h>
2#include <limits.h>
3
4// Utility function to find maximum of two numbers
5int max(int x, int y) {
6 return (x > y) ? x : y;
7}
8
9// Function to find maximum subarray sum using divide and conquer
10int maximum_sum(int A[], int low, int high)
11{
12 // If array contains only one element
13 if (high == low)
14 return A[low];
15
16 // Find middle element of the array
17 int mid = (low + high) / 2;
18
19 // Find maximum subarray sum for the left subarray
20 // including the middle element
21 int left_max = INT_MIN;
22 int sum = 0;
23 for (int i = mid; i >= low; i--)
24 {
25 sum += A[i];
26 if (sum > left_max)
27 left_max = sum;
28 }
29
30 // Find maximum subarray sum for the right subarray
31 // excluding the middle element
32 int right_max = INT_MIN;
33 sum = 0; // reset sum to 0
34 for (int i = mid + 1; i <= high; i++)
35 {
36 sum += A[i];
37 if (sum > right_max)
38 right_max = sum;
39 }
40
41 // Recursively find the maximum subarray sum for left subarray
42 // and right subarray and take maximum
43 int max_left_right = max(maximum_sum(A, low, mid),
44 maximum_sum(A, mid + 1, high));
45
46 // return maximum of the three
47 return max(max_left_right, left_max + right_max);
48}
49
50// Maximum Sum Subarray using Divide & Conquer
51int main(void)
52{
53 int arr[] = { 2, -4, 1, 9, -6, 7, -3 };
54 int n = sizeof(arr) / sizeof(arr[0]);
55
56 printf("The maximum sum of the subarray is %d",
57 maximum_sum(arr, 0, n - 1));
58
59 return 0;
60}
61