print maximum sum subarray
To print the maximum sum subarray in C++, you can follow these steps:
- Initialize variables: Start by initializing three variables:
maxSoFar
,maxEndingHere
, andstart
. SetmaxSoFar
andmaxEndingHere
to 0, andstart
to 0. These variables will keep track of the maximum sum found so far, the maximum sum ending at the current position, and the starting index of the maximum sum subarray.
int maxSoFar = 0;
int maxEndingHere = 0;
int start = 0;
- Iterate through the array: Use a loop to iterate through the given array. Start the loop from index 0 and continue until the end of the array.
for (int i = 0; i < n; i++) {
// ...
}
- Update
maxEndingHere
: Inside the loop, updatemaxEndingHere
by adding the current element to it. IfmaxEndingHere
becomes negative, reset it to 0.
maxEndingHere = maxEndingHere + arr[i];
if (maxEndingHere < 0) {
maxEndingHere = 0;
}
- Update
maxSoFar
andstart
: After updatingmaxEndingHere
, check if it is greater thanmaxSoFar
. If it is, updatemaxSoFar
andstart
accordingly.
if (maxEndingHere > maxSoFar) {
maxSoFar = maxEndingHere;
start = i;
}
- Print the subarray: After the loop ends, you can print the subarray with the maximum sum. Iterate from
start
toi
(which represents the end of the subarray) and print the elements.
for (int j = start; j <= i; j++) {
cout << arr[j] << " ";
}
Putting it all together, here's the complete code:
#include <iostream>
using namespace std;
void printMaxSubarray(int arr[], int n) {
int maxSoFar = 0;
int maxEndingHere = 0;
int start = 0;
for (int i = 0; i < n; i++) {
maxEndingHere = maxEndingHere + arr[i];
if (maxEndingHere < 0) {
maxEndingHere = 0;
}
if (maxEndingHere > maxSoFar) {
maxSoFar = maxEndingHere;
start = i;
}
}
for (int j = start; j <= i; j++) {
cout << arr[j] << " ";
}
}
int main() {
int arr[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
int n = sizeof(arr) / sizeof(arr[0]);
printMaxSubarray(arr, n);
return 0;
}
This code will find and print the subarray with the maximum sum.