Skip to content

Commit 9d371bc

Browse files
committed
Largest Contiguous Sum in Array
1 parent ad05e3a commit 9d371bc

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

largest_contiguous_array_sum.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include<iostream>
2+
#include<climits>
3+
using namespace std;
4+
5+
int maxSumSubarray(int a[], int n)
6+
{
7+
// Function to find the contiguous subarray whose sum is maximum in the array and also print this subarray
8+
int i, max_total = INT_MIN, max_curr = 0, s =0, e = 0, x=0;
9+
for(i=0; i<n; i++)
10+
{
11+
max_curr += a[i];
12+
if (max_total < max_curr)
13+
{
14+
max_total = max_curr;
15+
s = x;
16+
e = i;
17+
}
18+
if (max_curr < 0)
19+
{
20+
max_curr = 0;
21+
x = i + 1;
22+
}
23+
}
24+
cout<<"Maximum Contiguous Sum in the given array: "<<max_total<<endl;
25+
cout<<"Max Subarray: ";
26+
for(i=s; i<=e; i++)
27+
cout<<a[i]<<" ";
28+
}
29+
30+
int main()
31+
{
32+
int a[100], n;
33+
cout<<"Enter the no. of elements in the array: ";
34+
cin>>n;
35+
cout<<"Enter the elements of the array: \n";
36+
for(int i=0;i<n;i++)
37+
cin>>a[i];
38+
maxSumSubarray(a, n);
39+
return 0;
40+
}

0 commit comments

Comments
 (0)