find maximum sum in array of contiguous subarrays
To find the maximum sum in an array of contiguous subarrays in C++, you can use the Kadane's algorithm. Here are the steps:
Initialize two variables,
max_so_far
andmax_ending_here
, to track the maximum sum. Set both variables to 0 initially.Iterate through the array, element by element.
For each element, add it to the
max_ending_here
variable.If the
max_ending_here
variable becomes negative, reset it to 0. This is because a negative sum will only decrease the overall maximum sum.If the
max_ending_here
variable is greater than themax_so_far
variable, update themax_so_far
variable with themax_ending_here
value.After iterating through the entire array, the
max_so_far
variable will contain the maximum sum of any contiguous subarray in the array.
Here is an example implementation of the Kadane's algorithm in C++:
#include <iostream>
using namespace std;
int findMaxSubarraySum(int arr[], int size) {
int max_so_far = 0;
int max_ending_here = 0;
for (int i = 0; i < size; i++) {
max_ending_here = max_ending_here + arr[i];
if (max_ending_here < 0) {
max_ending_here = 0;
}
if (max_so_far < max_ending_here) {
max_so_far = max_ending_here;
}
}
return max_so_far;
}
int main() {
int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3};
int size = sizeof(arr) / sizeof(arr[0]);
int maxSum = findMaxSubarraySum(arr, size);
cout << "Maximum sum of a contiguous subarray: " << maxSum << endl;
return 0;
}
This implementation will output: Maximum sum of a contiguous subarray: 7
, which corresponds to the maximum sum of the subarray {4, -1, -2, 1, 5}
.