From a1e2f70459fb09ea29f43a2ebc11c80eca793bb0 Mon Sep 17 00:00:00 2001 From: Saurabh prajapati Date: Fri, 21 Oct 2022 10:59:28 +0530 Subject: [PATCH] code to find maximum sum of sub-array --- Kedane_algorithum.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Kedane_algorithum.cpp diff --git a/Kedane_algorithum.cpp b/Kedane_algorithum.cpp new file mode 100644 index 0000000..ea87827 --- /dev/null +++ b/Kedane_algorithum.cpp @@ -0,0 +1,38 @@ + + +#include +#include +using namespace std; + +void 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<<"\n"; + + cout << "Starting index " << start << endl + << "Ending index " << end << endl; +} + +int main() +{ + int a[] = { 5,9,-2, -3, 4, -1, -2, 1, 5, -3 }; + int n = sizeof(a) / sizeof(a[0]); + int max_sum = maxSubArraySum(a, n); + return 0; +}