From b0c940f581518ba70e2e02a42ee5fea40c9f9781 Mon Sep 17 00:00:00 2001 From: prajjwaljoshi <88524726+prajjwaljoshi@users.noreply.github.com> Date: Fri, 21 Oct 2022 18:56:43 +0530 Subject: [PATCH] Create C++ program to print largest contiguous array sum --- ...gram to print largest contiguous array sum | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/C++ program to print largest contiguous array sum diff --git a/C++/C++ program to print largest contiguous array sum b/C++/C++ program to print largest contiguous array sum new file mode 100644 index 0000000..1da78fd --- /dev/null +++ b/C++/C++ program to print largest contiguous array sum @@ -0,0 +1,30 @@ +// C++ program to print largest contiguous array sum +#include +using namespace std; + +int maxSubArraySum(int a[], int size) +{ + int max_so_far = INT_MIN, max_ending_here = 0; + + for (int i = 0; i < size; i++) { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; +} + +// Driver Code +int main() +{ + int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; + int n = sizeof(a) / sizeof(a[0]); + + // Function Call + int max_sum = maxSubArraySum(a, n); + cout << "Maximum contiguous sum is " << max_sum; + return 0; +}