This repository has been archived by the owner on Oct 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 299
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #44 from saurass/master
Largest Sum Contiguous Subarray in c++
- Loading branch information
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |