-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxsubarr.cpp
More file actions
73 lines (57 loc) · 1.92 KB
/
maxsubarr.cpp
File metadata and controls
73 lines (57 loc) · 1.92 KB
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
70
71
72
73
#include <iostream>
using namespace std;
// Function to find the maximum sum of subarray crossing the midpoint
int maxCrossingSum(int arr[], int left, int mid, int right) {
int leftSum = -1000000; // Manually set a very small value instead of INT_MIN
int rightSum = -1000000;
int sum = 0;
// Find maximum sum in the left half
for (int i = mid; i >= left; i--) {
sum += arr[i];
if (sum > leftSum) {
leftSum = sum;
}
}
sum = 0;
// Find maximum sum in the right half
for (int i = mid + 1; i <= right; i++) {
sum += arr[i];
if (sum > rightSum) {
rightSum = sum;
}
}
// Return sum of left, right, and crossing subarray
return leftSum + rightSum;
}
// Divide and conquer function to find the maximum subarray sum
int maxSubArraySum(int arr[], int left, int right) {
// Base case: if there is only one element
if (left == right) {
return arr[left];
}
// Find the middle point
int mid = (left + right) / 2;
// Recursively find the maximum subarray sum for the left and right halves
int leftSum = maxSubArraySum(arr, left, mid);
int rightSum = maxSubArraySum(arr, mid + 1, right);
// Find the maximum sum of the subarray that crosses the midpoint
int crossSum = maxCrossingSum(arr, left, mid, right);
// Return the maximum of the three
return max(max(leftSum, rightSum), crossSum);
}
int main() {
int n;
// Input the size of the array
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];
// Input the elements of the array
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
// Call the divide and conquer function to find the maximum subarray sum
int result = maxSubArraySum(arr, 0, n - 1);
cout << "The maximum subarray sum is: " << result << endl;
return 0;
}