Skip to content
This repository has been archived by the owner on Oct 1, 2021. It is now read-only.

Commit

Permalink
Merge pull request #44 from saurass/master
Browse files Browse the repository at this point in the history
Largest Sum Contiguous Subarray in c++
  • Loading branch information
Harshsngh07 committed Sep 25, 2020
2 parents e7324b2 + 4d0361f commit 4e253f4
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions Language/C++/LargestSumContiguousSubarray.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// C++ program to print largest contiguous array sum

#include<iostream>
#include<climits>
using namespace std;

int maxSubArraySum(int a[], int size)
{
int max_so_far = INT_MIN, max_ending_here = 0,
start =0, end = 0, s=0;

for (int i=0; i< size; i++ )
{
max_ending_here += a[i];

if (max_so_far < max_ending_here)
{
max_so_far = max_ending_here;
start = s;
end = i;
}

if (max_ending_here < 0)
{
max_ending_here = 0;
s = i + 1;
}
}
cout << "Maximum contiguous sum is "
<< max_so_far << endl;
cout << "Starting index "<< start
<< endl << "Ending index "<< end << endl;
}

int main()
{
int n;
cout << "Enter number of elements in array \n";
cin >> n;

int a[n];
for(int i = 0; i < n; i++) {
cout << "Enter element " << i + 1 << " -\n";
cin >> a[i];
}
int max_sum = maxSubArraySum(a, n);
return 0;
}

0 comments on commit 4e253f4

Please sign in to comment.