forked from MainakRepositor/500-CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
100.cpp
69 lines (60 loc) · 1.72 KB
/
100.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// A Divide and Conquer based program for maximum subarray
// sum problem
#include <limits.h>
#include <stdio.h>
// A utility funtion to find maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }
// A utility funtion to find maximum of three integers
int max(int a, int b, int c) { return max(max(a, b), c); }
// Find the maximum possible sum in arr[] auch that arr[m]
// is part of it
int maxCrossingSum(int arr[], int l, int m, int h)
{
// Include elements on left of mid.
int sum = 0;
int left_sum = INT_MIN;
for (int i = m; i >= l; i--) {
sum = sum + arr[i];
if (sum > left_sum)
left_sum = sum;
}
// Include elements on right of mid
sum = 0;
int right_sum = INT_MIN;
for (int i = m + 1; i <= h; i++) {
sum = sum + arr[i];
if (sum > right_sum)
right_sum = sum;
}
// Return sum of elements on left and right of mid
// returning only left_sum + right_sum will fail for
// [-2, 1]
return max(left_sum + right_sum, left_sum, right_sum);
}
// Returns sum of maxium sum subarray in aa[l..h]
int maxSubArraySum(int arr[], int l, int h)
{
// Base Case: Only one element
if (l == h)
return arr[l];
// Find middle point
int m = (l + h) / 2;
/* Return maximum of following three possible cases
a) Maximum subarray sum in left half
b) Maximum subarray sum in right half
c) Maximum subarray sum such that the subarray
crosses the midpoint */
return max(maxSubArraySum(arr, l, m),
maxSubArraySum(arr, m + 1, h),
maxCrossingSum(arr, l, m, h));
}
/*Driver program to test maxSubArraySum*/
int main()
{
int arr[] = { 2, 3, 4, 5, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
int max_sum = maxSubArraySum(arr, 0, n - 1);
printf("Maximum contiguous sum is %dn", max_sum);
getchar();
return 0;
}