#include <bits/stdc++.h>
using namespace std;
void printpair(int ar[], int n)
{
int largestsum = INT_MIN, currentsum = 0;
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
currentsum = 0;
largestsum = INT_MIN;
for (int k = i; k <= j; k++)
{
cout << ar[k] << ",";
currentsum += ar[k];
}
cout << "\n";
}
largestsum = max(largestsum, currentsum);
cout << "the largest sum is " << largestsum << endl;
}
}
int main()
{
int n;
cin >> n;
int ar[n];
for (int i = 0; i < n; i++)
cin >> ar[i];
printpair(ar, n);
}
When I input:
5
-5 5 6 -7 1
I'm getting output from the first iteration of the outer loop as
-5,
-5,5,
-5,5,6,
-5,5,6,-7,
-5,5,6,-7,1,
the largest sum is 0
...
But it should be 6
as -5 + 5 + 6 = 6
so the largest sum of subarray must be 6
, but here it is 0
, why!?