-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMax_SubArray.cpp
More file actions
35 lines (25 loc) · 835 Bytes
/
Max_SubArray.cpp
File metadata and controls
35 lines (25 loc) · 835 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include<bits/stdc++.h>
using namespace std;
void largestSub(vector<int> &array){
int currentSum = 0, totalSum = INT_MIN;
for(int i=0; i<array.size(); i++) {
//Sum till this point = Current Sum till this point + this element
currentSum = currentSum + array[i];
//If the current maximum array sum is greater than the global total. Update it
totalSum = max(totalSum, currentSum);
//If you get current as less than 0, Make it 0
currentSum = max(0,currentSum);
}
cout<<"The sum is: "<<totalSum;
}
int main(){
vector<int> array;
int n;
cin>>n;
for(int i=0;i<n;++i){
int x;
cin>>x;
array.push_back(x);
}
largestSub(array);
}