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

Optimized Implementation of Kadane's Algorithm for Maximum Subarray Sum in C++ #1342

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
65 changes: 22 additions & 43 deletions C++/Kadanes_Algorithm.cpp
Original file line number Diff line number Diff line change
@@ -1,58 +1,37 @@
// Github Username: amitShindeGit
#include <iostream>
#include <vector>
#include <algorithm> // For using std::max
using namespace std;

class Solution{
public:
// arr: input array
// n: size of array
//Function to find the sum of contiguous subarray with maximum sum.
long long max(long long x, long long y){
if(x > y){
return x;
}else{
return y;
}
}

long long maxSubarraySum(int arr[], int n){

// Your code here
class Solution {
public:
// Function to find the sum of the contiguous subarray with the maximum sum
long long maxSubarraySum(vector<int>& arr, int n) {
long long max_current = arr[0];
long long max_global = arr[0];

for(int i=1; i<=n-1; i++){
max_current = max(arr[i], max_current + arr[i]);
// cout << max_current << " " << max_global << endl;

if(max_current > max_global){
max_global = max_current;
}

for (int i = 1; i < n; ++i) {
max_current = max((long long)arr[i], max_current + arr[i]);
max_global = max(max_global, max_current);
}

return max_global;

}
};


int main()
{
int t,n;
int main() {
int t, n;

cin>>t; //input testcases
while(t--) //while testcases exist
{
cin >> t; // input test cases
while (t--) {
cin >> n; // input size of array

cin>>n; //input size of array

int a[n];
vector<int> arr(n);
for (int i = 0; i < n; ++i) {
cin >> arr[i]; // inputting elements of array
}

for(int i=0;i<n;i++)
cin>>a[i]; //inputting elements of array

Solution ob;

cout << ob.maxSubarraySum(a, n) << endl;
cout << ob.maxSubarraySum(arr, n) << endl;
}
}
}