From f473b182a7d70170465abd229e594c3202f47ea2 Mon Sep 17 00:00:00 2001 From: Vanshika Rathod <85212298+vanshikaaaaaaaa@users.noreply.github.com> Date: Mon, 14 Oct 2024 16:48:06 +0530 Subject: [PATCH] Created new file : Kadane's algo added a file --- c++/Kadane's algo | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 c++/Kadane's algo diff --git a/c++/Kadane's algo b/c++/Kadane's algo new file mode 100644 index 0000000..af97a1e --- /dev/null +++ b/c++/Kadane's algo @@ -0,0 +1,41 @@ +// MAXIMUM SUBARRAY SUM ON AN ARRAY + + +#include +using namespace std; + +long long maxSubarraySum(int arr[], int n) { + long long maxi = LONG_MIN; // maximum sum + long long sum = 0; + + for (int i = 0; i < n; i++) { + + sum += arr[i]; + + if (sum > maxi) { + maxi = sum; + } + + // If sum < 0: discard the sum calculated + if (sum < 0) { + sum = 0; + } + } + + // To consider the sum of the empty subarray + // uncomment the following check: + + //if (maxi < 0) maxi = 0; + + return maxi; +} + +int main() +{ + int arr[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4}; + int n = sizeof(arr) / sizeof(arr[0]); + long long maxSum = maxSubarraySum(arr, n); + cout << "The maximum subarray sum is: " << maxSum << endl; + return 0; +} +