From 4d0361f977e43b613e47c66cf58dc0986b5bb93f Mon Sep 17 00:00:00 2001 From: Saurabh Srivastava Date: Fri, 18 Oct 2019 09:45:42 +0530 Subject: [PATCH] Largest Sum Contiguous Subarray in c++ Signed-off-by: Saurabh Srivastava --- Language/C++/LargestSumContiguousSubarray.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Language/C++/LargestSumContiguousSubarray.cpp diff --git a/Language/C++/LargestSumContiguousSubarray.cpp b/Language/C++/LargestSumContiguousSubarray.cpp new file mode 100644 index 00000000..49451acf --- /dev/null +++ b/Language/C++/LargestSumContiguousSubarray.cpp @@ -0,0 +1,48 @@ +// C++ program to print largest contiguous array sum + +#include +#include +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; +}