-
Notifications
You must be signed in to change notification settings - Fork 387
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added code for "Maximum Subarray Sum"
- Loading branch information
1 parent
cce4b4f
commit 62b45eb
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |