Skip to content

Commit

Permalink
Merge pull request #518 from manvika-10/patch-2
Browse files Browse the repository at this point in the history
Added code for "Maximum Subarray Sum"
  • Loading branch information
tanus786 authored Oct 26, 2022
2 parents a87df77 + 62b45eb commit 704fa89
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions MaxSubarraySum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//Time Complexity : O(N)
//Space Complexity : O(1)

#include<bits/stdc++.h>
using namespace std;

int maxSubArraySum(int arr[], int size)
{
int max_sum = INT_MIN, ending_index = 0;

for(int i=0; i<size; i++)
{
ending_index = ending_index + arr[i];
if(max_sum < ending_index)
{
max_sum = ending_index;
}
if(ending_index < 0)
{
ending_index = 0;
}
}
return max_sum;
}

int main()
{
int arr[] = {4,-3,4,-1,-5,1,9,-6};
int n = sizeof(arr)/sizeof(arr[0]);

int ans = maxSubArraySum(arr,n);
cout << "Maximum Subarray Sum :" << ans;
return 0;
}

0 comments on commit 704fa89

Please sign in to comment.