Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created new file : Kadane's algo #346

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions c++/Kadane's algo
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// MAXIMUM SUBARRAY SUM ON AN ARRAY


#include <bits/stdc++.h>
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;
}