0
#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!?

anastaciu
  • 23,467
  • 7
  • 28
  • 53

2 Answers2

1

You are not saving the max sum value, you need to do it within the loop:

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++)
            {
                std::cout << ar[k] << ",";
                currentsum += ar[k];
                largestsum = std::max(largestsum, currentsum);
            }
            std::cout << "\n";
        }
        std::cout << "the largest sum is " << largestsum << std::endl;
    }
}

Note that variable length arrays are not C++ standard, you should not use them, I would also advise you not to use using namespace std; and #include <bits/stdc++.h>;, here are some threads with more on these matters:

Why aren't variable-length arrays part of the C++ standard?

Why is "using namespace std;" considered bad practice?

Why should I not #include <bits/stdc++.h>?

anastaciu
  • 23,467
  • 7
  • 28
  • 53
0

You are setting

          largestsum = INT_MIN;

in the inner loop.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339