Wednesday 22 November 2017

C++ Program to Find the maximum subarray sum O(n^2) time(naive method)


Code:

#include    iostream

using namespace std;

int main()
{
int n, i, j, max=-1, sum, imax, fmax;
cout<<"\nEnter the number of data element in the array: ";
cin>>n;

    int a[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<
cin>>a[i];
}

// Loop for the length of the sub-array.
for(i = 1; i < n+1; i++)
{
sum = 0;
// Loop for the maximizing the sum of the element of the sub array of length 'i'.
for(j = 0; j < n; j++)
{
// First pick the first sub array of 'i' length.
if(j < i)
sum += a[j];
// Add the next element and subtract the first element from the sub-array.
else
sum = sum+a[j]-a[j-i];

// Compare the sum with the global maximum of each length.
if(max < sum )
{
// Assign the initial and the final indexes to the imax and the fmax variables and update the max, if condition satisfies.
imax = j-i+1;
fmax = j;
max = sum;
}
}
}

// Print the maximum sum sub-array and their sum.
cout<<"\nThe maximum sub array is: ";
for(i = imax; i <= fmax; i++)
cout<
cout<<"\nThe maximum sub-array sum is: "<
}



Output:

Case 1:
Enter the number of data element in the array: 10
Enter element 1: 2
Enter element 2: 2
Enter element 3: -5
Enter element 4: 4
Enter element 5: -5
Enter element 6: -6
Enter element 7: -7
Enter element 8: 8
Enter element 9: 8
Enter element 10: -16

The maximum sub-array is: 8 8
The maximum sub-array sum is: 16



More C++ Programs:















100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...